home *** CD-ROM | disk | FTP | other *** search
/ Aminet 48 / Aminet 48 (2002)(GTI - Schatztruhe)[!][Apr 2002].iso / Aminet / text / edit / vim60src.lha / Vim / vim60 / src / misc1.c < prev    next >
Encoding:
C/C++ Source or Header  |  2001-09-26  |  161.3 KB  |  7,035 lines

  1. /* vi:set ts=8 sts=4 sw=4:
  2.  *
  3.  * VIM - Vi IMproved    by Bram Moolenaar
  4.  *
  5.  * Do ":help uganda"  in Vim to read copying and usage conditions.
  6.  * Do ":help credits" in Vim to see a list of people who contributed.
  7.  * See README.txt for an overview of the Vim source code.
  8.  */
  9.  
  10. /*
  11.  * misc1.c: functions that didn't seem to fit elsewhere
  12.  */
  13.  
  14. #include "vim.h"
  15. #include "version.h"
  16.  
  17. #ifdef HAVE_FCNTL_H
  18. # include <fcntl.h>        /* for chdir() */
  19. #endif
  20.  
  21. static char_u *vim_version_dir __ARGS((char_u *vimdir));
  22. static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
  23. #if defined(USE_EXE_NAME) && defined(MACOS_X)
  24. static char_u *remove_tail_with_ext __ARGS((char_u *p, char_u *pend, char_u *name));
  25. #endif
  26. static int get_indent_str __ARGS((char_u *ptr, int ts));
  27.  
  28. /*
  29.  * Count the size (in window cells) of the indent in the current line.
  30.  */
  31.     int
  32. get_indent()
  33. {
  34.     return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
  35. }
  36.  
  37. /*
  38.  * Count the size (in window cells) of the indent in line "lnum".
  39.  */
  40.     int
  41. get_indent_lnum(lnum)
  42.     linenr_T    lnum;
  43. {
  44.     return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
  45. }
  46.  
  47. #if defined(FEAT_FOLDING) || defined(PROTO)
  48. /*
  49.  * Count the size (in window cells) of the indent in line "lnum" of buffer
  50.  * "buf".
  51.  */
  52.     int
  53. get_indent_buf(buf, lnum)
  54.     buf_T    *buf;
  55.     linenr_T    lnum;
  56. {
  57.     return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
  58. }
  59. #endif
  60.  
  61. /*
  62.  * count the size (in window cells) of the indent in line "ptr", with
  63.  * 'tabstop' at "ts"
  64.  */
  65.     static int
  66. get_indent_str(ptr, ts)
  67.     char_u    *ptr;
  68.     int        ts;
  69. {
  70.     int        count = 0;
  71.  
  72.     for ( ; *ptr; ++ptr)
  73.     {
  74.     if (*ptr == TAB)    /* count a tab for what it is worth */
  75.         count += ts - (count % ts);
  76.     else if (*ptr == ' ')
  77.         ++count;        /* count a space for one */
  78.     else
  79.         break;
  80.     }
  81.     return (count);
  82. }
  83.  
  84. /*
  85.  * Set the indent of the current line.
  86.  * Leaves the cursor on the first non-blank in the line.
  87.  * Caller must take care of undo.
  88.  * "flags":
  89.  *    SIN_CHANGED:    call changed_bytes() if the line was changed.
  90.  *    SIN_INSERT:    insert the indent in front of the line.
  91.  *    SIN_UNDO:    save line for undo before changing it.
  92.  * Returns TRUE if the line was changed.
  93.  */
  94.     int
  95. set_indent(size, flags)
  96.     int        size;
  97.     int        flags;
  98. {
  99.     char_u    *p;
  100.     char_u    *line;
  101.     char_u    *s;
  102.     int        todo;
  103.     int        ind_len;
  104.     int        line_len;
  105.     int        doit = FALSE;
  106.  
  107.     /*
  108.      * First check if there is anything to do and compute the number of
  109.      * characters needed for the indent.
  110.      */
  111.     todo = size;
  112.     ind_len = 0;
  113.     p = ml_get_curline();
  114.     if (!curbuf->b_p_et)    /* if 'expandtab' isn't set: use TABs */
  115.     while (todo >= (int)curbuf->b_p_ts)
  116.     {
  117.         if (*p != TAB)
  118.         doit = TRUE;
  119.         else
  120.         ++p;
  121.         todo -= curbuf->b_p_ts;
  122.         ++ind_len;
  123.     }
  124.     while (todo > 0)
  125.     {
  126.     if (*p != ' ')
  127.         doit = TRUE;
  128.     else
  129.         ++p;
  130.     --todo;
  131.     ++ind_len;
  132.     }
  133.  
  134.     /* Return if the indent is OK already. */
  135.     if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
  136.     return FALSE;
  137.  
  138.     /* Allocate memory for the new line. */
  139.     if (flags & SIN_INSERT)
  140.     p = ml_get_curline();
  141.     else
  142.     p = skipwhite(p);
  143.     line_len = (int)STRLEN(p) + 1;
  144.     line = alloc(ind_len + line_len);
  145.     if (line == NULL)
  146.     return FALSE;
  147.  
  148.     /* Put the characters in the new line. */
  149.     s = line;
  150.     todo = size;
  151.     if (!curbuf->b_p_et)    /* if 'expandtab' isn't set: use TABs */
  152.     while (todo >= (int)curbuf->b_p_ts)
  153.     {
  154.         *s++ = TAB;
  155.         todo -= (int)curbuf->b_p_ts;
  156.     }
  157.     while (todo > 0)
  158.     {
  159.     *s++ = ' ';
  160.     --todo;
  161.     }
  162.     mch_memmove(s, p, (size_t)line_len);
  163.  
  164.     /* Replace the line (unless undo fails). */
  165.     if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
  166.     {
  167.     ml_replace(curwin->w_cursor.lnum, line, FALSE);
  168.     if (flags & SIN_CHANGED)
  169.         changed_bytes(curwin->w_cursor.lnum, 0);
  170.     }
  171.     else
  172.     vim_free(line);
  173.  
  174.     curwin->w_cursor.col = ind_len;
  175.     return TRUE;
  176. }
  177.  
  178. /*
  179.  * Return the indent of the current line after a number.  Return -1 if no
  180.  * number was found.  Used for '1' in 'formatoptions': numbered list.
  181.  */
  182.     int
  183. get_number_indent(lnum)
  184.     linenr_T    lnum;
  185. {
  186.     char_u    *line;
  187.     char_u    *p;
  188.     colnr_T    col;
  189.     pos_T    pos;
  190.  
  191.     if (lnum > curbuf->b_ml.ml_line_count)
  192.     return -1;
  193.     line = ml_get(lnum);
  194.     p = skipwhite(line);
  195.     if (!isdigit(*p))
  196.     return -1;
  197.     p = skipdigits(p);
  198.     if (vim_strchr((char_u *)":.)]}\t ", *p) == NULL)
  199.     return -1;
  200.     p = skipwhite(p + 1);
  201.     if (*p == NUL)
  202.     return -1;
  203.     pos.lnum = lnum;
  204.     pos.col = (colnr_T)(p - line);
  205.     getvcol(curwin, &pos, &col, NULL, NULL);
  206.     return (int)col;
  207. }
  208.  
  209. #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
  210.  
  211. static int cin_is_cinword __ARGS((char_u *line));
  212.  
  213. /*
  214.  * Return TRUE if the string "line" starts with a word from 'cinwords'.
  215.  */
  216.     static int
  217. cin_is_cinword(line)
  218.     char_u    *line;
  219. {
  220.     char_u    *cinw;
  221.     char_u    *cinw_buf;
  222.     int        cinw_len;
  223.     int        retval = FALSE;
  224.     int        len;
  225.  
  226.     cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
  227.     cinw_buf = alloc((unsigned)cinw_len);
  228.     if (cinw_buf != NULL)
  229.     {
  230.     line = skipwhite(line);
  231.     for (cinw = curbuf->b_p_cinw; *cinw; )
  232.     {
  233.         len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
  234.         if (STRNCMP(line, cinw_buf, len) == 0
  235.             && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
  236.         {
  237.         retval = TRUE;
  238.         break;
  239.         }
  240.     }
  241.     vim_free(cinw_buf);
  242.     }
  243.     return retval;
  244. }
  245. #endif
  246.  
  247. /*
  248.  * open_line: Add a new line below or above the current line.
  249.  *
  250.  * For VREPLACE mode, we only add a new line when we get to the end of the
  251.  * file, otherwise we just start replacing the next line.
  252.  *
  253.  * Caller must take care of undo.  Since VREPLACE may affect any number of
  254.  * lines however, it may call u_save_cursor() again when starting to change a
  255.  * new line.
  256.  *
  257.  * Return TRUE for success, FALSE for failure
  258.  */
  259.     int
  260. open_line(dir, flags, old_indent)
  261.     int        dir;        /* FORWARD or BACKWARD */
  262.     int        flags;        /* OPENLINE_DELSPACES and OPENLINE_DO_COM */
  263.     int        old_indent;    /* indent for after ^^D in Insert mode */
  264. {
  265.     char_u    *saved_line;        /* copy of the original line */
  266.     char_u    *next_line = NULL;    /* copy of the next line */
  267.     char_u    *p_extra = NULL;    /* what goes to next line */
  268.     pos_T    old_cursor;        /* old cursor position */
  269.     int        newcol = 0;        /* new cursor column */
  270.     int        newindent = 0;        /* auto-indent of the new line */
  271.     int        n;
  272.     int        trunc_line = FALSE;    /* truncate current line afterwards */
  273.     int        retval = FALSE;        /* return value, default is FAIL */
  274. #ifdef FEAT_COMMENTS
  275.     int        extra_len = 0;        /* length of p_extra string */
  276.     int        lead_len;        /* length of comment leader */
  277.     char_u    *lead_flags;    /* position in 'comments' for comment leader */
  278.     char_u    *leader = NULL;        /* copy of comment leader */
  279. #endif
  280.     char_u    *allocated = NULL;    /* allocated memory */
  281. #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
  282.     || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
  283.     char_u    *p;
  284. #endif
  285.     int        saved_char = NUL;    /* init for GCC */
  286. #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
  287.     pos_T    *pos;
  288. #endif
  289. #ifdef FEAT_SMARTINDENT
  290.     int        do_si = (!p_paste && curbuf->b_p_si
  291. # ifdef FEAT_CINDENT
  292.                     && !curbuf->b_p_cin
  293. # endif
  294.             );
  295.     int        no_si = FALSE;        /* reset did_si afterwards */
  296.     int        first_char = NUL;    /* init for GCC */
  297. #endif
  298. #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
  299.     int        vreplace_mode;
  300. #endif
  301.     int        did_append;        /* appended a new line */
  302.  
  303.     /*
  304.      * make a copy of the current line so we can mess with it
  305.      */
  306.     saved_line = vim_strsave(ml_get_curline());
  307.     if (saved_line == NULL)        /* out of memory! */
  308.     return FALSE;
  309.  
  310. #ifdef FEAT_VREPLACE
  311.     if (State & VREPLACE_FLAG)
  312.     {
  313.     /*
  314.      * With VREPLACE we make a copy of the next line, which we will be
  315.      * starting to replace.  First make the new line empty and let vim play
  316.      * with the indenting and comment leader to its heart's content.  Then
  317.      * we grab what it ended up putting on the new line, put back the
  318.      * original line, and call ins_char() to put each new character onto
  319.      * the line, replacing what was there before and pushing the right
  320.      * stuff onto the replace stack.  -- webb.
  321.      */
  322.     if (curwin->w_cursor.lnum < orig_line_count)
  323.         next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
  324.     else
  325.         next_line = vim_strsave((char_u *)"");
  326.     if (next_line == NULL)        /* out of memory! */
  327.         goto theend;
  328.  
  329.     /*
  330.      * In VREPLACE mode, a NL replaces the rest of the line, and starts
  331.      * replacing the next line, so push all of the characters left on the
  332.      * line onto the replace stack.  We'll push any other characters that
  333.      * might be replaced at the start of the next line (due to autoindent
  334.      * etc) a bit later.
  335.      */
  336.     replace_push(NUL);  /* Call twice because BS over NL expects it */
  337.     replace_push(NUL);
  338.     p = saved_line + curwin->w_cursor.col;
  339.     while (*p != NUL)
  340.         replace_push(*p++);
  341.     saved_line[curwin->w_cursor.col] = NUL;
  342.     }
  343. #endif
  344.  
  345.     if ((State & INSERT)
  346. #ifdef FEAT_VREPLACE
  347.         && !(State & VREPLACE_FLAG)
  348. #endif
  349.         )
  350.     {
  351.     p_extra = saved_line + curwin->w_cursor.col;
  352. #ifdef FEAT_SMARTINDENT
  353.     if (do_si)        /* need first char after new line break */
  354.     {
  355.         p = skipwhite(p_extra);
  356.         first_char = *p;
  357.     }
  358. #endif
  359. #ifdef FEAT_COMMENTS
  360.     extra_len = (int)STRLEN(p_extra);
  361. #endif
  362.     saved_char = *p_extra;
  363.     *p_extra = NUL;
  364.     }
  365.  
  366.     u_clearline();        /* cannot do "U" command when adding lines */
  367. #ifdef FEAT_SMARTINDENT
  368.     did_si = FALSE;
  369. #endif
  370.     ai_col = 0;
  371.  
  372.     /*
  373.      * If we just did an auto-indent, then we didn't type anything on
  374.      * the prior line, and it should be truncated.  Do this even if 'ai' is not
  375.      * set because automatically inserting a comment leader also sets did_ai.
  376.      */
  377.     if (dir == FORWARD && did_ai)
  378.     trunc_line = TRUE;
  379.  
  380.     /*
  381.      * If 'autoindent' and/or 'smartindent' is set, try to figure out what
  382.      * indent to use for the new line.
  383.      */
  384.     if (curbuf->b_p_ai
  385. #ifdef FEAT_SMARTINDENT
  386.             || do_si
  387. #endif
  388.                         )
  389.     {
  390.     /*
  391.      * count white space on current line
  392.      */
  393.     newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
  394.     if (newindent == 0)
  395.         newindent = old_indent;    /* for ^^D command in insert mode */
  396.  
  397. #ifdef FEAT_SMARTINDENT
  398.     /*
  399.      * Do smart indenting.
  400.      * In insert/replace mode (only when dir == FORWARD)
  401.      * we may move some text to the next line. If it starts with '{'
  402.      * don't add an indent. Fixes inserting a NL before '{' in line
  403.      *    "if (condition) {"
  404.      */
  405.     if (!trunc_line && do_si && *saved_line != NUL
  406.                     && (p_extra == NULL || first_char != '{'))
  407.     {
  408.         char_u  *ptr;
  409.         char_u  last_char;
  410.  
  411.         old_cursor = curwin->w_cursor;
  412.         ptr = saved_line;
  413. # ifdef FEAT_COMMENTS
  414.         if (flags & OPENLINE_DO_COM)
  415.         lead_len = get_leader_len(ptr, NULL, FALSE);
  416.         else
  417.         lead_len = 0;
  418. # endif
  419.         if (dir == FORWARD)
  420.         {
  421.         /*
  422.          * Skip preprocessor directives, unless they are
  423.          * recognised as comments.
  424.          */
  425.         if (
  426. # ifdef FEAT_COMMENTS
  427.             lead_len == 0 &&
  428. # endif
  429.             ptr[0] == '#')
  430.         {
  431.             while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
  432.             ptr = ml_get(--curwin->w_cursor.lnum);
  433.             newindent = get_indent();
  434.         }
  435. # ifdef FEAT_COMMENTS
  436.         if (flags & OPENLINE_DO_COM)
  437.             lead_len = get_leader_len(ptr, NULL, FALSE);
  438.         else
  439.             lead_len = 0;
  440.         if (lead_len > 0)
  441.         {
  442.             /*
  443.              * This case gets the following right:
  444.              *        \*
  445.              *         * A comment (read '\' as '/').
  446.              *         *\
  447.              * #define IN_THE_WAY
  448.              *        This should line up here;
  449.              */
  450.             p = skipwhite(ptr);
  451.             if (p[0] == '/' && p[1] == '*')
  452.             p++;
  453.             if (p[0] == '*')
  454.             {
  455.             for (p++; *p; p++)
  456.             {
  457.                 if (p[0] == '/' && p[-1] == '*')
  458.                 {
  459.                 /*
  460.                  * End of C comment, indent should line up
  461.                  * with the line containing the start of
  462.                  * the comment
  463.                  */
  464.                 curwin->w_cursor.col = (colnr_T)(p - ptr);
  465.                 if ((pos = findmatch(NULL, NUL)) != NULL)
  466.                 {
  467.                     curwin->w_cursor.lnum = pos->lnum;
  468.                     newindent = get_indent();
  469.                 }
  470.                 }
  471.             }
  472.             }
  473.         }
  474.         else    /* Not a comment line */
  475. # endif
  476.         {
  477.             /* Find last non-blank in line */
  478.             p = ptr + STRLEN(ptr) - 1;
  479.             while (p > ptr && vim_iswhite(*p))
  480.             --p;
  481.             last_char = *p;
  482.  
  483.             /*
  484.              * find the character just before the '{' or ';'
  485.              */
  486.             if (last_char == '{' || last_char == ';')
  487.             {
  488.             if (p > ptr)
  489.                 --p;
  490.             while (p > ptr && vim_iswhite(*p))
  491.                 --p;
  492.             }
  493.             /*
  494.              * Try to catch lines that are split over multiple
  495.              * lines.  eg:
  496.              *        if (condition &&
  497.              *            condition) {
  498.              *        Should line up here!
  499.              *        }
  500.              */
  501.             if (*p == ')')
  502.             {
  503.             curwin->w_cursor.col = (colnr_T)(p - ptr);
  504.             if ((pos = findmatch(NULL, '(')) != NULL)
  505.             {
  506.                 curwin->w_cursor.lnum = pos->lnum;
  507.                 newindent = get_indent();
  508.                 ptr = ml_get_curline();
  509.             }
  510.             }
  511.             /*
  512.              * If last character is '{' do indent, without
  513.              * checking for "if" and the like.
  514.              */
  515.             if (last_char == '{')
  516.             {
  517.             did_si = TRUE;    /* do indent */
  518.             no_si = TRUE;    /* don't delete it when '{' typed */
  519.             }
  520.             /*
  521.              * Look for "if" and the like, use 'cinwords'.
  522.              * Don't do this if the previous line ended in ';' or
  523.              * '}'.
  524.              */
  525.             else if (last_char != ';' && last_char != '}'
  526.                                && cin_is_cinword(ptr))
  527.             did_si = TRUE;
  528.         }
  529.         }
  530.         else /* dir == BACKWARD */
  531.         {
  532.         /*
  533.          * Skip preprocessor directives, unless they are
  534.          * recognised as comments.
  535.          */
  536.         if (
  537. # ifdef FEAT_COMMENTS
  538.             lead_len == 0 &&
  539. # endif
  540.             ptr[0] == '#')
  541.         {
  542.             int was_backslashed = FALSE;
  543.  
  544.             while ((ptr[0] == '#' || was_backslashed) &&
  545.              curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
  546.             {
  547.             if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
  548.                 was_backslashed = TRUE;
  549.             else
  550.                 was_backslashed = FALSE;
  551.             ptr = ml_get(++curwin->w_cursor.lnum);
  552.             }
  553.             if (was_backslashed)
  554.             newindent = 0;        /* Got to end of file */
  555.             else
  556.             newindent = get_indent();
  557.         }
  558.         p = skipwhite(ptr);
  559.         if (*p == '}')        /* if line starts with '}': do indent */
  560.             did_si = TRUE;
  561.         else            /* can delete indent when '{' typed */
  562.             can_si_back = TRUE;
  563.         }
  564.         curwin->w_cursor = old_cursor;
  565.     }
  566.     if (do_si)
  567.         can_si = TRUE;
  568. #endif /* FEAT_SMARTINDENT */
  569.  
  570.     did_ai = TRUE;
  571.     }
  572.  
  573. #ifdef FEAT_COMMENTS
  574.     /*
  575.      * Find out if the current line starts with a comment leader.
  576.      * This may then be inserted in front of the new line.
  577.      */
  578.     end_comment_pending = NUL;
  579.     if (flags & OPENLINE_DO_COM)
  580.     lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
  581.     else
  582.     lead_len = 0;
  583.     if (lead_len > 0)
  584.     {
  585.     char_u    *lead_repl = NULL;        /* replaces comment leader */
  586.     int    lead_repl_len = 0;        /* length of *lead_repl */
  587.     char_u    lead_middle[COM_MAX_LEN];   /* middle-comment string */
  588.     char_u    lead_end[COM_MAX_LEN];        /* end-comment string */
  589.     char_u    *comment_end = NULL;        /* where lead_end has been found */
  590.     int    extra_space = FALSE;        /* append extra space */
  591.     int    current_flag;
  592.     int    require_blank = FALSE;        /* requires blank after middle */
  593.     char_u    *p2;
  594.  
  595.     /*
  596.      * If the comment leader has the start, middle or end flag, it may not
  597.      * be used or may be replaced with the middle leader.
  598.      */
  599.     for (p = lead_flags; *p && *p != ':'; ++p)
  600.     {
  601.         if (*p == COM_BLANK)
  602.         {
  603.         require_blank = TRUE;
  604.         continue;
  605.         }
  606.         if (*p == COM_START || *p == COM_MIDDLE)
  607.         {
  608.         current_flag = *p;
  609.         if (*p == COM_START)
  610.         {
  611.             /*
  612.              * Doing "O" on a start of comment does not insert leader.
  613.              */
  614.             if (dir == BACKWARD)
  615.             {
  616.             lead_len = 0;
  617.             break;
  618.             }
  619.  
  620.             /* find start of middle part */
  621.             (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
  622.             require_blank = FALSE;
  623.         }
  624.  
  625.         /*
  626.          * Isolate the strings of the middle and end leader.
  627.          */
  628.         while (*p && p[-1] != ':')    /* find end of middle flags */
  629.         {
  630.             if (*p == COM_BLANK)
  631.             require_blank = TRUE;
  632.             ++p;
  633.         }
  634.         (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
  635.  
  636.         while (*p && p[-1] != ':')    /* find end of end flags */
  637.         {
  638.             /* Check whether we allow automatic ending of comments */
  639.             if (*p == COM_AUTO_END)
  640.             end_comment_pending = -1; /* means we want to set it */
  641.             ++p;
  642.         }
  643.         n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
  644.  
  645.         if (end_comment_pending == -1)    /* we can set it now */
  646.             end_comment_pending = lead_end[n - 1];
  647.  
  648.         /*
  649.          * If the end of the comment is in the same line, don't use
  650.          * the comment leader.
  651.          */
  652.         if (dir == FORWARD)
  653.         {
  654.             for (p = saved_line + lead_len; *p; ++p)
  655.             if (STRNCMP(p, lead_end, n) == 0)
  656.             {
  657.                 comment_end = p;
  658.                 lead_len = 0;
  659.                 break;
  660.             }
  661.         }
  662.  
  663.         /*
  664.          * Doing "o" on a start of comment inserts the middle leader.
  665.          */
  666.         if (lead_len > 0)
  667.         {
  668.             if (current_flag == COM_START)
  669.             {
  670.             lead_repl = lead_middle;
  671.             lead_repl_len = (int)STRLEN(lead_middle);
  672.             }
  673.  
  674.             /*
  675.              * If we have hit RETURN immediately after the start
  676.              * comment leader, then put a space after the middle
  677.              * comment leader on the next line.
  678.              */
  679.             if (!vim_iswhite(saved_line[lead_len - 1])
  680.                 && ((p_extra != NULL
  681.                     && (int)curwin->w_cursor.col == lead_len)
  682.                 || (p_extra == NULL
  683.                     && saved_line[lead_len] == NUL)
  684.                 || require_blank))
  685.             extra_space = TRUE;
  686.         }
  687.         break;
  688.         }
  689.         if (*p == COM_END)
  690.         {
  691.         /*
  692.          * Doing "o" on the end of a comment does not insert leader.
  693.          * Remember where the end is, might want to use it to find the
  694.          * start (for C-comments).
  695.          */
  696.         if (dir == FORWARD)
  697.         {
  698.             comment_end = skipwhite(saved_line);
  699.             lead_len = 0;
  700.             break;
  701.         }
  702.  
  703.         /*
  704.          * Doing "O" on the end of a comment inserts the middle leader.
  705.          * Find the string for the middle leader, searching backwards.
  706.          */
  707.         while (p > curbuf->b_p_com && *p != ',')
  708.             --p;
  709.         for (lead_repl = p; lead_repl > curbuf->b_p_com
  710.                      && lead_repl[-1] != ':'; --lead_repl)
  711.             ;
  712.         lead_repl_len = (int)(p - lead_repl);
  713.  
  714.         /* We can probably always add an extra space when doing "O" on
  715.          * the comment-end */
  716.         extra_space = TRUE;
  717.  
  718.         /* Check whether we allow automatic ending of comments */
  719.         for (p2 = p; *p2 && *p2 != ':'; p2++)
  720.         {
  721.             if (*p2 == COM_AUTO_END)
  722.             end_comment_pending = -1; /* means we want to set it */
  723.         }
  724.         if (end_comment_pending == -1)
  725.         {
  726.             /* Find last character in end-comment string */
  727.             while (*p2 && *p2 != ',')
  728.             p2++;
  729.             end_comment_pending = p2[-1];
  730.         }
  731.         break;
  732.         }
  733.         if (*p == COM_FIRST)
  734.         {
  735.         /*
  736.          * Comment leader for first line only:    Don't repeat leader
  737.          * when using "O", blank out leader when using "o".
  738.          */
  739.         if (dir == BACKWARD)
  740.             lead_len = 0;
  741.         else
  742.         {
  743.             lead_repl = (char_u *)"";
  744.             lead_repl_len = 0;
  745.         }
  746.         break;
  747.         }
  748.     }
  749.     if (lead_len)
  750.     {
  751.         /* allocate buffer (may concatenate p_exta later) */
  752.         leader = alloc(lead_len + lead_repl_len + extra_space +
  753.                                   extra_len + 1);
  754.         allocated = leader;            /* remember to free it later */
  755.  
  756.         if (leader == NULL)
  757.         lead_len = 0;
  758.         else
  759.         {
  760.         STRNCPY(leader, saved_line, lead_len);
  761.         leader[lead_len] = NUL;
  762.  
  763.         /*
  764.          * Replace leader with lead_repl, right or left adjusted
  765.          */
  766.         if (lead_repl != NULL)
  767.         {
  768.             int        c = 0;
  769.             int        off = 0;
  770.  
  771.             for (p = lead_flags; *p && *p != ':'; ++p)
  772.             {
  773.             if (*p == COM_RIGHT || *p == COM_LEFT)
  774.                 c = *p;
  775.             else if (isdigit(*p) || *p == '-')
  776.                 off = getdigits(&p);
  777.             }
  778.             if (c == COM_RIGHT)    /* right adjusted leader */
  779.             {
  780.             /* find last non-white in the leader to line up with */
  781.             for (p = leader + lead_len - 1; p > leader
  782.                               && vim_iswhite(*p); --p)
  783.                 ;
  784.  
  785.             ++p;
  786.             if (p < leader + lead_repl_len)
  787.                 p = leader;
  788.             else
  789.                 p -= lead_repl_len;
  790.             mch_memmove(p, lead_repl, (size_t)lead_repl_len);
  791.             if (p + lead_repl_len > leader + lead_len)
  792.                 p[lead_repl_len] = NUL;
  793.  
  794.             /* blank-out any other chars from the old leader. */
  795.             while (--p >= leader)
  796.                 if (!vim_iswhite(*p))
  797.                 *p = ' ';
  798.             }
  799.             else            /* left adjusted leader */
  800.             {
  801.             p = skipwhite(leader);
  802.             mch_memmove(p, lead_repl, (size_t)lead_repl_len);
  803.  
  804.             /* Replace any remaining non-white chars in the old
  805.              * leader by spaces.  Keep Tabs, the indent must
  806.              * remain the same. */
  807.             for (p += lead_repl_len; p < leader + lead_len; ++p)
  808.                 if (!vim_iswhite(*p))
  809.                 {
  810.                 /* Don't put a space before a TAB. */
  811.                 if (p + 1 < leader + lead_len && p[1] == TAB)
  812.                 {
  813.                     --lead_len;
  814.                     mch_memmove(p, p + 1,
  815.                              (leader + lead_len) - p);
  816.                 }
  817.                 else
  818.                     *p = ' ';
  819.                 }
  820.             *p = NUL;
  821.             }
  822.  
  823.             /* Recompute the indent, it may have changed. */
  824.             if (curbuf->b_p_ai
  825. #ifdef FEAT_SMARTINDENT
  826.                     || do_si
  827. #endif
  828.                                )
  829.             newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
  830.  
  831.             /* Add the indent offset */
  832.             if (newindent + off < 0)
  833.             {
  834.             off = -newindent;
  835.             newindent = 0;
  836.             }
  837.             else
  838.             newindent += off;
  839.  
  840.             /* Correct trailing spaces for the shift, so that
  841.              * alignment remains equal. */
  842.             while (off > 0 && lead_len > 0
  843.                            && leader[lead_len - 1] == ' ')
  844.             {
  845.             /* Don't do it when there is a tab before the space */
  846.             if (vim_strchr(skipwhite(leader), '\t') != NULL)
  847.                 break;
  848.             --lead_len;
  849.             --off;
  850.             }
  851.  
  852.             /* If the leader ends in white space, don't add an
  853.              * extra space */
  854.             if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
  855.             extra_space = FALSE;
  856.             leader[lead_len] = NUL;
  857.         }
  858.  
  859.         if (extra_space)
  860.         {
  861.             leader[lead_len++] = ' ';
  862.             leader[lead_len] = NUL;
  863.         }
  864.  
  865.         newcol = lead_len;
  866.  
  867.         /*
  868.          * if a new indent will be set below, remove the indent that
  869.          * is in the comment leader
  870.          */
  871.         if (newindent
  872. #ifdef FEAT_SMARTINDENT
  873.                 || did_si
  874. #endif
  875.                        )
  876.         {
  877.             while (lead_len && vim_iswhite(*leader))
  878.             {
  879.             --lead_len;
  880.             --newcol;
  881.             ++leader;
  882.             }
  883.         }
  884.  
  885.         }
  886. #ifdef FEAT_SMARTINDENT
  887.         did_si = can_si = FALSE;
  888. #endif
  889.     }
  890.     else if (comment_end != NULL)
  891.     {
  892.         /*
  893.          * We have finished a comment, so we don't use the leader.
  894.          * If this was a C-comment and 'ai' or 'si' is set do a normal
  895.          * indent to align with the line containing the start of the
  896.          * comment.
  897.          */
  898.         if (comment_end[0] == '*' && comment_end[1] == '/' &&
  899.             (curbuf->b_p_ai
  900. #ifdef FEAT_SMARTINDENT
  901.                     || do_si
  902. #endif
  903.                                ))
  904.         {
  905.         old_cursor = curwin->w_cursor;
  906.         curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
  907.         if ((pos = findmatch(NULL, NUL)) != NULL)
  908.         {
  909.             curwin->w_cursor.lnum = pos->lnum;
  910.             newindent = get_indent();
  911.         }
  912.         curwin->w_cursor = old_cursor;
  913.         }
  914.     }
  915.     }
  916. #endif
  917.  
  918.     /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
  919.     if (p_extra != NULL)
  920.     {
  921.     *p_extra = saved_char;        /* restore char that NUL replaced */
  922.  
  923.     /*
  924.      * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
  925.      * non-blank.
  926.      *
  927.      * When in REPLACE mode, put the deleted blanks on the replace stack,
  928.      * preceded by a NUL, so they can be put back when a BS is entered.
  929.      */
  930.     if (REPLACE_NORMAL(State))
  931.         replace_push(NUL);        /* end of extra blanks */
  932.     if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
  933.     {
  934.         while (*p_extra == ' ' || *p_extra == '\t')
  935.         {
  936.         if (REPLACE_NORMAL(State))
  937.             replace_push(*p_extra);
  938.         ++p_extra;
  939.         }
  940.     }
  941.     if (*p_extra != NUL)
  942.         did_ai = FALSE;        /* append some text, don't truncate now */
  943.     }
  944.  
  945.     if (p_extra == NULL)
  946.     p_extra = (char_u *)"";            /* append empty line */
  947.  
  948. #ifdef FEAT_COMMENTS
  949.     /* concatenate leader and p_extra, if there is a leader */
  950.     if (lead_len)
  951.     {
  952.     STRCAT(leader, p_extra);
  953.     p_extra = leader;
  954.     did_ai = TRUE;        /* So truncating blanks works with comments */
  955.     }
  956.     else
  957.     end_comment_pending = NUL;  /* turns out there was no leader */
  958. #endif
  959.  
  960.     old_cursor = curwin->w_cursor;
  961.     if (dir == BACKWARD)
  962.     --curwin->w_cursor.lnum;
  963. #ifdef FEAT_VREPLACE
  964.     if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
  965. #endif
  966.     {
  967.     if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
  968.                                       == FAIL)
  969.         goto theend;
  970.     /* Postpone calling changed_lines(), because it would mess up folding
  971.      * with markers. */
  972.     mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
  973.     did_append = TRUE;
  974.     }
  975. #ifdef FEAT_VREPLACE
  976.     else
  977.     {
  978.     /*
  979.      * In VREPLACE mode we are starting to replace the next line.
  980.      */
  981.     curwin->w_cursor.lnum++;
  982.     if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
  983.     {
  984.         /* In case we NL to a new line, BS to the previous one, and NL
  985.          * again, we don't want to save the new line for undo twice.
  986.          */
  987.         (void)u_save_cursor();            /* errors are ignored! */
  988.         vr_lines_changed++;
  989.     }
  990.     ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
  991.     changed_bytes(curwin->w_cursor.lnum, 0);
  992.     curwin->w_cursor.lnum--;
  993.     did_append = FALSE;
  994.     }
  995. #endif
  996.  
  997.     if (newindent
  998. #ifdef FEAT_SMARTINDENT
  999.             || did_si
  1000. #endif
  1001.                 )
  1002.     {
  1003.     ++curwin->w_cursor.lnum;
  1004. #ifdef FEAT_SMARTINDENT
  1005.     if (did_si)
  1006.     {
  1007.         if (p_sr)
  1008.         newindent -= newindent % (int)curbuf->b_p_sw;
  1009.         newindent += (int)curbuf->b_p_sw;
  1010.     }
  1011. #endif
  1012.     (void)set_indent(newindent, SIN_INSERT);
  1013.     ai_col = curwin->w_cursor.col;
  1014.  
  1015.     /*
  1016.      * In REPLACE mode, for each character in the new indent, there must
  1017.      * be a NUL on the replace stack, for when it is deleted with BS
  1018.      */
  1019.     if (REPLACE_NORMAL(State))
  1020.         for (n = 0; n < (int)curwin->w_cursor.col; ++n)
  1021.         replace_push(NUL);
  1022.     newcol += curwin->w_cursor.col;
  1023. #ifdef FEAT_SMARTINDENT
  1024.     if (no_si)
  1025.         did_si = FALSE;
  1026. #endif
  1027.     }
  1028.  
  1029. #ifdef FEAT_COMMENTS
  1030.     /*
  1031.      * In REPLACE mode, for each character in the extra leader, there must be
  1032.      * a NUL on the replace stack, for when it is deleted with BS.
  1033.      */
  1034.     if (REPLACE_NORMAL(State))
  1035.     while (lead_len-- > 0)
  1036.         replace_push(NUL);
  1037. #endif
  1038.  
  1039.     curwin->w_cursor = old_cursor;
  1040.  
  1041.     if (dir == FORWARD)
  1042.     {
  1043.     if (trunc_line || (State & INSERT))
  1044.     {
  1045.         /* truncate current line at cursor */
  1046.         saved_line[curwin->w_cursor.col] = NUL;
  1047.         if (trunc_line)        /* Remove trailing white space */
  1048.         truncate_spaces(saved_line);
  1049.         ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
  1050.         saved_line = NULL;
  1051.         if (did_append)
  1052.         {
  1053.         changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
  1054.                            curwin->w_cursor.lnum + 1, 1L);
  1055.         did_append = FALSE;
  1056.         }
  1057.         else
  1058.         changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
  1059.     }
  1060.  
  1061.     /*
  1062.      * Put the cursor on the new line.  Careful: the scrollup() above may
  1063.      * have moved w_cursor, we must use old_cursor.
  1064.      */
  1065.     curwin->w_cursor.lnum = old_cursor.lnum + 1;
  1066.     }
  1067.     if (did_append)
  1068.     changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
  1069.  
  1070.     curwin->w_cursor.col = newcol;
  1071. #ifdef FEAT_VIRTUALEDIT
  1072.     curwin->w_cursor.coladd = 0;
  1073. #endif
  1074.  
  1075. #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
  1076.     /*
  1077.      * In VREPLACE mode, we are handling the replace stack ourselves, so stop
  1078.      * fixthisline() from doing it (via change_indent()) by telling it we're in
  1079.      * normal INSERT mode.
  1080.      */
  1081.     if (State & VREPLACE_FLAG)
  1082.     {
  1083.     vreplace_mode = State;    /* So we know to put things right later */
  1084.     State = INSERT;
  1085.     }
  1086.     else
  1087.     vreplace_mode = 0;
  1088. #endif
  1089. #ifdef FEAT_LISP
  1090.     /*
  1091.      * May do lisp indenting.
  1092.      */
  1093.     if (!p_paste
  1094. # ifdef FEAT_COMMENTS
  1095.         && leader == NULL
  1096. # endif
  1097.         && curbuf->b_p_lisp
  1098.         && curbuf->b_p_ai)
  1099.     {
  1100.     fixthisline(get_lisp_indent);
  1101.     p = ml_get_curline();
  1102.     ai_col = (colnr_T)(skipwhite(p) - p);
  1103.     }
  1104. #endif
  1105. #ifdef FEAT_CINDENT
  1106.     /*
  1107.      * May do indenting after opening a new line.
  1108.      */
  1109.     if (!p_paste
  1110. # ifdef FEAT_COMMENTS
  1111.         && (leader == NULL || !curbuf->b_p_ai)
  1112. # endif
  1113.         && (curbuf->b_p_cin
  1114. #  ifdef FEAT_EVAL
  1115.             || *curbuf->b_p_inde != NUL
  1116. #  endif
  1117.         )
  1118.         && in_cinkeys(dir == FORWARD
  1119.         ? KEY_OPEN_FORW
  1120.         : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
  1121.     {
  1122.     do_c_expr_indent();
  1123.     p = ml_get_curline();
  1124.     ai_col = (colnr_T)(skipwhite(p) - p);
  1125.     }
  1126. #endif
  1127. #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
  1128.     if (vreplace_mode != 0)
  1129.     State = vreplace_mode;
  1130. #endif
  1131.  
  1132. #ifdef FEAT_VREPLACE
  1133.     /*
  1134.      * Finally, VREPLACE gets the stuff on the new line, then puts back the
  1135.      * original line, and inserts the new stuff char by char, pushing old stuff
  1136.      * onto the replace stack (via ins_char()).
  1137.      */
  1138.     if (State & VREPLACE_FLAG)
  1139.     {
  1140.     /* Put new line in p_extra */
  1141.     p_extra = vim_strsave(ml_get_curline());
  1142.     if (p_extra == NULL)
  1143.         goto theend;
  1144.  
  1145.     /* Put back original line */
  1146.     ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
  1147.  
  1148.     /* Insert new stuff into line again */
  1149.     curwin->w_cursor.col = 0;
  1150. #ifdef FEAT_VIRTUALEDIT
  1151.     curwin->w_cursor.coladd = 0;
  1152. #endif
  1153.     ins_bytes(p_extra);    /* will call changed_bytes() */
  1154.     next_line = NULL;
  1155.     }
  1156. #endif
  1157.  
  1158.     retval = TRUE;        /* success! */
  1159. theend:
  1160.     vim_free(saved_line);
  1161.     vim_free(next_line);
  1162.     vim_free(allocated);
  1163.     return retval;
  1164. }
  1165.  
  1166. #if defined(FEAT_COMMENTS) || defined(PROTO)
  1167. /*
  1168.  * get_leader_len() returns the length of the prefix of the given string
  1169.  * which introduces a comment.    If this string is not a comment then 0 is
  1170.  * returned.
  1171.  * When "flags" is not NULL, it is set to point to the flags of the recognized
  1172.  * comment leader.
  1173.  * "backward" must be true for the "O" command.
  1174.  */
  1175.     int
  1176. get_leader_len(line, flags, backward)
  1177.     char_u    *line;
  1178.     char_u    **flags;
  1179.     int        backward;
  1180. {
  1181.     int        i, j;
  1182.     int        got_com = FALSE;
  1183.     int        found_one;
  1184.     char_u    part_buf[COM_MAX_LEN];    /* buffer for one option part */
  1185.     char_u    *string;        /* pointer to comment string */
  1186.     char_u    *list;
  1187.  
  1188.     i = 0;
  1189.     while (vim_iswhite(line[i]))    /* leading white space is ignored */
  1190.     ++i;
  1191.  
  1192.     /*
  1193.      * Repeat to match several nested comment strings.
  1194.      */
  1195.     while (line[i])
  1196.     {
  1197.     /*
  1198.      * scan through the 'comments' option for a match
  1199.      */
  1200.     found_one = FALSE;
  1201.     for (list = curbuf->b_p_com; *list; )
  1202.     {
  1203.         /*
  1204.          * Get one option part into part_buf[].  Advance list to next one.
  1205.          * put string at start of string.
  1206.          */
  1207.         if (!got_com && flags != NULL)  /* remember where flags started */
  1208.         *flags = list;
  1209.         (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
  1210.         string = vim_strchr(part_buf, ':');
  1211.         if (string == NULL)        /* missing ':', ignore this part */
  1212.         continue;
  1213.         *string++ = NUL;        /* isolate flags from string */
  1214.  
  1215.         /*
  1216.          * When already found a nested comment, only accept further
  1217.          * nested comments.
  1218.          */
  1219.         if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
  1220.         continue;
  1221.  
  1222.         /* When 'O' flag used don't use for "O" command */
  1223.         if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
  1224.         continue;
  1225.  
  1226.         /*
  1227.          * Line contents and string must match.
  1228.          * When string starts with white space, must have some white space
  1229.          * (but the amount does not need to match, there might be a mix of
  1230.          * TABs and spaces).
  1231.          */
  1232.         if (vim_iswhite(string[0]))
  1233.         {
  1234.         if (i == 0 || !vim_iswhite(line[i - 1]))
  1235.             continue;
  1236.         while (vim_iswhite(string[0]))
  1237.             ++string;
  1238.         }
  1239.         for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
  1240.         ;
  1241.         if (string[j] != NUL)
  1242.         continue;
  1243.  
  1244.         /*
  1245.          * When 'b' flag used, there must be white space or an
  1246.          * end-of-line after the string in the line.
  1247.          */
  1248.         if (vim_strchr(part_buf, COM_BLANK) != NULL
  1249.                && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
  1250.         continue;
  1251.  
  1252.         /*
  1253.          * We have found a match, stop searching.
  1254.          */
  1255.         i += j;
  1256.         got_com = TRUE;
  1257.         found_one = TRUE;
  1258.         break;
  1259.     }
  1260.  
  1261.     /*
  1262.      * No match found, stop scanning.
  1263.      */
  1264.     if (!found_one)
  1265.         break;
  1266.  
  1267.     /*
  1268.      * Include any trailing white space.
  1269.      */
  1270.     while (vim_iswhite(line[i]))
  1271.         ++i;
  1272.  
  1273.     /*
  1274.      * If this comment doesn't nest, stop here.
  1275.      */
  1276.     if (vim_strchr(part_buf, COM_NEST) == NULL)
  1277.         break;
  1278.     }
  1279.     return (got_com ? i : 0);
  1280. }
  1281. #endif
  1282.  
  1283. /*
  1284.  * Return the number of window lines occupied by buffer line "lnum".
  1285.  */
  1286.     int
  1287. plines(lnum)
  1288.     linenr_T    lnum;
  1289. {
  1290.     return plines_win(curwin, lnum, TRUE);
  1291. }
  1292.  
  1293.     int
  1294. plines_win(wp, lnum, winheight)
  1295.     win_T    *wp;
  1296.     linenr_T    lnum;
  1297.     int        winheight;    /* when TRUE limit to window height */
  1298. {
  1299. #if defined(FEAT_DIFF) || defined(PROTO)
  1300.     /* Check for filler lines above this buffer line.  When folded the result
  1301.      * is one line anyway. */
  1302.     return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
  1303. }
  1304.  
  1305.     int
  1306. plines_nofill(lnum)
  1307.     linenr_T    lnum;
  1308. {
  1309.     return plines_win_nofill(curwin, lnum, TRUE);
  1310. }
  1311.  
  1312.     int
  1313. plines_win_nofill(wp, lnum, winheight)
  1314.     win_T    *wp;
  1315.     linenr_T    lnum;
  1316.     int        winheight;    /* when TRUE limit to window height */
  1317. {
  1318. #endif
  1319.     int        lines;
  1320.  
  1321.     if (!wp->w_p_wrap)
  1322.     return 1;
  1323.  
  1324. #ifdef FEAT_VERTSPLIT
  1325.     if (wp->w_width == 0)
  1326.     return 1;
  1327. #endif
  1328.  
  1329. #ifdef FEAT_FOLDING
  1330.     /* A folded lines is handled just like an empty line. */
  1331.     /* NOTE: Caller must handle lines that are MAYBE folded. */
  1332.     if (lineFolded(wp, lnum) == TRUE)
  1333.     return 1;
  1334. #endif
  1335.  
  1336.     lines = plines_win_nofold(wp, lnum);
  1337.     if (winheight > 0 && lines > wp->w_height)
  1338.     return (int)wp->w_height;
  1339.     return lines;
  1340. }
  1341.  
  1342. /*
  1343.  * Return number of window lines physical line "lnum" will occupy in window
  1344.  * "wp".  Does not care about folding, 'wrap' or 'diff'.
  1345.  */
  1346.     int
  1347. plines_win_nofold(wp, lnum)
  1348.     win_T    *wp;
  1349.     linenr_T    lnum;
  1350. {
  1351.     char_u    *s;
  1352.     long    col;
  1353.     int        width;
  1354.  
  1355.     s = ml_get_buf(wp->w_buffer, lnum, FALSE);
  1356.     if (*s == NUL)        /* empty line */
  1357.     return 1;
  1358.     col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
  1359.  
  1360.     /*
  1361.      * If list mode is on, then the '$' at the end of the line may take up one
  1362.      * extra column.
  1363.      */
  1364.     if (wp->w_p_list && lcs_eol != NUL)
  1365.     col += 1;
  1366.  
  1367.     /*
  1368.      * Add column offset for 'number' and 'foldcolumn'.
  1369.      */
  1370.     width = W_WIDTH(wp) - win_col_off(wp);
  1371.     if (width <= 0)
  1372.     return 32000;
  1373.     if (col <= width)
  1374.     return 1;
  1375.     col -= width;
  1376.     width += win_col_off2(wp);
  1377.     return (col + (width - 1)) / width + 1;
  1378. }
  1379.  
  1380. /*
  1381.  * Like plines_win(), but only reports the number of physical screen lines
  1382.  * used from the start of the line to the given column number.
  1383.  */
  1384.     int
  1385. plines_win_col(wp, lnum, column)
  1386.     win_T    *wp;
  1387.     linenr_T    lnum;
  1388.     long    column;
  1389. {
  1390.     long    col;
  1391.     char_u    *s;
  1392.     int        lines = 0;
  1393.     int        width;
  1394.  
  1395. #ifdef FEAT_DIFF
  1396.     /* Check for filler lines above this buffer line.  When folded the result
  1397.      * is one line anyway. */
  1398.     lines = diff_check_fill(wp, lnum);
  1399. #endif
  1400.  
  1401.     if (!wp->w_p_wrap)
  1402.     return lines + 1;
  1403.  
  1404. #ifdef FEAT_VERTSPLIT
  1405.     if (wp->w_width == 0)
  1406.     return lines + 1;
  1407. #endif
  1408.  
  1409.     s = ml_get_buf(wp->w_buffer, lnum, FALSE);
  1410.  
  1411.     col = 0;
  1412.     while (*s != NUL && --column >= 0)
  1413.     {
  1414.     col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
  1415. #ifdef FEAT_MBYTE
  1416.     if (has_mbyte)
  1417.         s += (*mb_ptr2len_check)(s);
  1418.     else
  1419. #endif
  1420.         ++s;
  1421.     }
  1422.  
  1423.     /*
  1424.      * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
  1425.      * INSERT mode, then col must be adjusted so that it represents the last
  1426.      * screen position of the TAB.  This only fixes an error when the TAB wraps
  1427.      * from one screen line to the next (when 'columns' is not a multiple of
  1428.      * 'ts') -- webb.
  1429.      */
  1430.     if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
  1431.     col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
  1432.  
  1433.     /*
  1434.      * Add column offset for 'number', 'foldcolumn', etc.
  1435.      */
  1436.     width = W_WIDTH(wp) - win_col_off(wp);
  1437.     if (width > 0)
  1438.     {
  1439.     lines += 1;
  1440.     if (col >= width)
  1441.         lines += (col - width) / (width + win_col_off2(wp));
  1442.     if (lines <= wp->w_height)
  1443.         return lines;
  1444.     }
  1445.     return (int)(wp->w_height);        /* maximum length */
  1446. }
  1447.  
  1448.     int
  1449. plines_m_win(wp, first, last)
  1450.     win_T    *wp;
  1451.     linenr_T    first, last;
  1452. {
  1453.     int        count = 0;
  1454.  
  1455.     while (first <= last)
  1456.     {
  1457. #ifdef FEAT_FOLDING
  1458.     int    x;
  1459.  
  1460.     /* Check if there are any really folded lines, but also included lines
  1461.      * that are maybe folded. */
  1462.     x = foldedCount(wp, first, NULL);
  1463.     if (x > 0)
  1464.     {
  1465.         ++count;        /* count 1 for "+-- folded" line */
  1466.         first += x;
  1467.     }
  1468.     else
  1469. #endif
  1470.     {
  1471. #ifdef FEAT_DIFF
  1472.         if (first == wp->w_topline)
  1473.         count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
  1474.         else
  1475. #endif
  1476.         count += plines_win(wp, first, TRUE);
  1477.         ++first;
  1478.     }
  1479.     }
  1480.     return (count);
  1481. }
  1482.  
  1483. #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
  1484. /*
  1485.  * Insert string "p" at the cursor position.  Stops at a NUL byte.
  1486.  * Handles Replace mode and multi-byte characters.
  1487.  */
  1488.     void
  1489. ins_bytes(p)
  1490.     char_u    *p;
  1491. {
  1492.     ins_bytes_len(p, (int)STRLEN(p));
  1493. }
  1494. #endif
  1495.  
  1496. #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
  1497.     || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
  1498. /*
  1499.  * Insert string "p" with length "len" at the cursor position.
  1500.  * Handles Replace mode and multi-byte characters.
  1501.  */
  1502.     void
  1503. ins_bytes_len(p, len)
  1504.     char_u    *p;
  1505.     int        len;
  1506. {
  1507.     int        i;
  1508. # ifdef FEAT_MBYTE
  1509.     int        n;
  1510.  
  1511.     for (i = 0; i < len; i += n)
  1512.     {
  1513.     n = (*mb_ptr2len_check)(p + i);
  1514.     ins_char_bytes(p + i, n);
  1515.     }
  1516. # else
  1517.     for (i = 0; i < len; ++i)
  1518.     ins_char(p[i]);
  1519. # endif
  1520. }
  1521. #endif
  1522.  
  1523. /*
  1524.  * Insert or replace a single character at the cursor position.
  1525.  * When in REPLACE or VREPLACE mode, replace any existing character.
  1526.  * Caller must have prepared for undo.
  1527.  * For multi-byte characters we get the whole character, the caller must
  1528.  * convert bytes to a character.
  1529.  */
  1530.     void
  1531. ins_char(c)
  1532.     int        c;
  1533. {
  1534. #if defined(FEAT_MBYTE) || defined(PROTO)
  1535.     char_u    buf[MB_MAXBYTES];
  1536.     int        n;
  1537.  
  1538.     n = (*mb_char2bytes)(c, buf);
  1539.     ins_char_bytes(buf, n);
  1540. }
  1541.  
  1542.     void
  1543. ins_char_bytes(buf, charlen)
  1544.     char_u    *buf;
  1545.     int        charlen;
  1546. {
  1547.     int        c = buf[0];
  1548.     int        l, j;
  1549. #endif
  1550.     int        newlen;        /* nr of bytes inserted */
  1551.     int        oldlen;        /* nr of bytes deleted (0 when not replacing) */
  1552.     char_u    *p;
  1553.     char_u    *newp;
  1554.     char_u    *oldp;
  1555.     int        linelen;    /* length of old line including NUL */
  1556.     colnr_T    col;
  1557.     linenr_T    lnum = curwin->w_cursor.lnum;
  1558.     int        i;
  1559.  
  1560. #ifdef FEAT_VIRTUALEDIT
  1561.     /* Break tabs if needed. */
  1562.     if (virtual_active() && curwin->w_cursor.coladd > 0)
  1563.     coladvance_force(getviscol());
  1564. #endif
  1565.  
  1566.     col = curwin->w_cursor.col;
  1567.     oldp = ml_get(lnum);
  1568.     linelen = (int)STRLEN(oldp) + 1;
  1569.  
  1570.     /* The lengths default to the values for when not replacing. */
  1571.     oldlen = 0;
  1572. #ifdef FEAT_MBYTE
  1573.     newlen = charlen;
  1574. #else
  1575.     newlen = 1;
  1576. #endif
  1577.  
  1578.     if (State & REPLACE_FLAG)
  1579.     {
  1580. #ifdef FEAT_VREPLACE
  1581.     if (State & VREPLACE_FLAG)
  1582.     {
  1583.         colnr_T    new_vcol = 0;   /* init for GCC */
  1584.         colnr_T    vcol;
  1585.         int        old_list;
  1586. #ifndef FEAT_MBYTE
  1587.         char_u    buf[2];
  1588. #endif
  1589.  
  1590.         /*
  1591.          * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
  1592.          * Returns the old value of list, so when finished,
  1593.          * curwin->w_p_list should be set back to this.
  1594.          */
  1595.         old_list = curwin->w_p_list;
  1596.         if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
  1597.         curwin->w_p_list = FALSE;
  1598.  
  1599.         /*
  1600.          * In virtual replace mode each character may replace one or more
  1601.          * characters (zero if it's a TAB).  Count the number of bytes to
  1602.          * be deleted to make room for the new character, counting screen
  1603.          * cells.  May result in adding spaces to fill a gap.
  1604.          */
  1605.         getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
  1606. #ifndef FEAT_MBYTE
  1607.         buf[0] = c;
  1608.         buf[1] = NUL;
  1609. #endif
  1610.         new_vcol = vcol + chartabsize(buf, vcol);
  1611.         while (oldp[col + oldlen] != NUL && vcol < new_vcol)
  1612.         {
  1613.         vcol += chartabsize(oldp + col + oldlen, vcol);
  1614.         /* Don't need to remove a TAB that takes us to the right
  1615.          * position. */
  1616.         if (vcol > new_vcol && oldp[col + oldlen] == TAB)
  1617.             break;
  1618. #ifdef FEAT_MBYTE
  1619.         oldlen += (*mb_ptr2len_check)(oldp + col + oldlen);
  1620. #else
  1621.         ++oldlen;
  1622. #endif
  1623.         /* Deleted a bit too much, insert spaces. */
  1624.         if (vcol > new_vcol)
  1625.             newlen += vcol - new_vcol;
  1626.         }
  1627.         curwin->w_p_list = old_list;
  1628.     }
  1629.     else
  1630. #endif
  1631.         if (oldp[col] != NUL)
  1632.     {
  1633.         /* normal replace */
  1634. #ifdef FEAT_MBYTE
  1635.         oldlen = (*mb_ptr2len_check)(oldp + col);
  1636. #else
  1637.         oldlen = 1;
  1638. #endif
  1639.     }
  1640.  
  1641.  
  1642.     /* Push the replaced bytes onto the replace stack, so that they can be
  1643.      * put back when BS is used.  The bytes of a multi-byte character are
  1644.      * done the other way around, so that the first byte is popped off
  1645.      * first (it tells the byte length of the character). */
  1646.     replace_push(NUL);
  1647.     for (i = 0; i < oldlen; ++i)
  1648.     {
  1649. #ifdef FEAT_MBYTE
  1650.         l = (*mb_ptr2len_check)(oldp + col + i) - 1;
  1651.         for (j = l; j >= 0; --j)
  1652.         replace_push(oldp[col + i + j]);
  1653.         i += l;
  1654. #else
  1655.         replace_push(oldp[col + i]);
  1656. #endif
  1657.     }
  1658.     }
  1659.  
  1660.     newp = alloc_check((unsigned)(linelen + newlen - oldlen));
  1661.     if (newp == NULL)
  1662.     return;
  1663.  
  1664.     /* Copy bytes before the cursor. */
  1665.     if (col > 0)
  1666.     mch_memmove(newp, oldp, (size_t)col);
  1667.  
  1668.     /* Copy bytes after the changed character(s). */
  1669.     p = newp + col;
  1670.     mch_memmove(p + newlen, oldp + col + oldlen,
  1671.                         (size_t)(linelen - col - oldlen));
  1672.  
  1673.     /* Insert or overwrite the new character. */
  1674. #ifdef FEAT_MBYTE
  1675.     mch_memmove(p, buf, charlen);
  1676.     i = charlen;
  1677. #else
  1678.     *p = c;
  1679.     i = 1;
  1680. #endif
  1681.  
  1682.     /* Fill with spaces when necessary. */
  1683.     while (i < newlen)
  1684.     p[i++] = ' ';
  1685.  
  1686.     /* Replace the line in the buffer. */
  1687.     ml_replace(lnum, newp, FALSE);
  1688.  
  1689.     /* mark the buffer as changed and prepare for displaying */
  1690.     changed_bytes(lnum, col);
  1691.  
  1692.     /*
  1693.      * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
  1694.      * show the match for right parens and braces.
  1695.      */
  1696.     if (p_sm && (State & INSERT)
  1697.         && msg_silent == 0
  1698. #ifdef FEAT_MBYTE
  1699.         && charlen == 1
  1700. #endif
  1701. #ifdef FEAT_RIGHTLEFT
  1702.         && ((!(curwin->w_p_rl ^ p_ri)
  1703.             && (c == ')' || c == '}' || c == ']'))
  1704.         || ((curwin->w_p_rl ^ p_ri)
  1705.             && (c == '(' || c == '{' || c == '[')))
  1706. #else
  1707.         && (c == ')' || c == '}' || c == ']')
  1708. #endif
  1709.         )
  1710.     showmatch();
  1711.  
  1712. #ifdef FEAT_RIGHTLEFT
  1713.     if (!p_ri || (State & REPLACE_FLAG))
  1714. #endif
  1715.     {
  1716.     /* Normal insert: move cursor right */
  1717. #ifdef FEAT_MBYTE
  1718.     curwin->w_cursor.col += charlen;
  1719. #else
  1720.     ++curwin->w_cursor.col;
  1721. #endif
  1722.     }
  1723.     /*
  1724.      * TODO: should try to update w_row here, to avoid recomputing it later.
  1725.      */
  1726. }
  1727.  
  1728. /*
  1729.  * Insert a string at the cursor position.
  1730.  * Note: Does NOT handle Replace mode.
  1731.  * Caller must have prepared for undo.
  1732.  */
  1733.     void
  1734. ins_str(s)
  1735.     char_u    *s;
  1736. {
  1737.     char_u    *oldp, *newp;
  1738.     int        newlen = (int)STRLEN(s);
  1739.     int        oldlen;
  1740.     colnr_T    col;
  1741.     linenr_T    lnum = curwin->w_cursor.lnum;
  1742.  
  1743. #ifdef FEAT_VIRTUALEDIT
  1744.     if (virtual_active() && curwin->w_cursor.coladd > 0)
  1745.     coladvance_force(getviscol());
  1746. #endif
  1747.  
  1748.     col = curwin->w_cursor.col;
  1749.     oldp = ml_get(lnum);
  1750.     oldlen = (int)STRLEN(oldp);
  1751.  
  1752.     newp = alloc_check((unsigned)(oldlen + newlen + 1));
  1753.     if (newp == NULL)
  1754.     return;
  1755.     if (col > 0)
  1756.     mch_memmove(newp, oldp, (size_t)col);
  1757.     mch_memmove(newp + col, s, (size_t)newlen);
  1758.     mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
  1759.     ml_replace(lnum, newp, FALSE);
  1760.     changed_bytes(lnum, col);
  1761.     curwin->w_cursor.col += newlen;
  1762. }
  1763.  
  1764. /*
  1765.  * Delete one character under the cursor.
  1766.  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
  1767.  * Caller must have prepared for undo.
  1768.  *
  1769.  * return FAIL for failure, OK otherwise
  1770.  */
  1771.     int
  1772. del_char(fixpos)
  1773.     int        fixpos;
  1774. {
  1775. #ifdef FEAT_MBYTE
  1776.     if (has_mbyte)
  1777.     {
  1778.     /* Make sure the cursor is at the start of a character. */
  1779.     mb_adjust_cursor();
  1780.     if (*ml_get_cursor() == NUL)
  1781.         return FAIL;
  1782.     return del_chars(1L, fixpos);
  1783.     }
  1784. #endif
  1785.     return del_bytes(1L, fixpos);
  1786. }
  1787.  
  1788. #if defined(FEAT_MBYTE) || defined(PROTO)
  1789. /*
  1790.  * Like del_bytes(), but delete characters instead of bytes.
  1791.  */
  1792.     int
  1793. del_chars(count, fixpos)
  1794.     long    count;
  1795.     int        fixpos;
  1796. {
  1797.     long    bytes = 0;
  1798.     long    i;
  1799.     char_u    *p;
  1800.     int        l;
  1801.  
  1802.     p = ml_get_cursor();
  1803.     for (i = 0; i < count && *p != NUL; ++i)
  1804.     {
  1805.     l = (*mb_ptr2len_check)(p);
  1806.     bytes += l;
  1807.     p += l;
  1808.     }
  1809.     return del_bytes(bytes, fixpos);
  1810. }
  1811. #endif
  1812.  
  1813. /*
  1814.  * Delete "count" bytes under the cursor.
  1815.  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
  1816.  * Caller must have prepared for undo.
  1817.  *
  1818.  * return FAIL for failure, OK otherwise
  1819.  */
  1820.     int
  1821. del_bytes(count, fixpos)
  1822.     long    count;
  1823.     int        fixpos;
  1824. {
  1825.     char_u    *oldp, *newp;
  1826.     colnr_T    oldlen;
  1827.     linenr_T    lnum = curwin->w_cursor.lnum;
  1828.     colnr_T    col = curwin->w_cursor.col;
  1829.     int        was_alloced;
  1830.     long    movelen;
  1831. #ifdef FEAT_MBYTE
  1832.     int        p0, p1, p2;
  1833.     int        p0len, p1len, p2len;
  1834. #endif
  1835.  
  1836.     oldp = ml_get(lnum);
  1837.     oldlen = (int)STRLEN(oldp);
  1838.  
  1839.     /*
  1840.      * Can't do anything when the cursor is on the NUL after the line.
  1841.      */
  1842.     if (col >= oldlen)
  1843.     return FAIL;
  1844.  
  1845. #ifdef FEAT_MBYTE
  1846.     if (p_deco && enc_utf8)
  1847.     {
  1848.     p1 = p2 = 0;
  1849.     /* see if there are any combining characters: */
  1850.     p0 = utfc_ptr2char(oldp + col, &p1, &p2);
  1851.     p0len = utf_char2len(p0);
  1852.     p1len = p1 != 0 ? utf_char2len(p1) : 0;
  1853.     p2len = p2 != 0 ? utf_char2len(p2) : 0;
  1854.  
  1855.     /* don't try anything if trying to del more than one 'char' */
  1856.     if ((count <= (p0len + p1len + p2len)) && p1 != 0)
  1857.     {
  1858.         /* We are here because there are combining characters; either
  1859.          * p1, p2 or both.  We need to remove just that character, and
  1860.          * leave the cursor where it was. */
  1861.  
  1862.         /* since p1 is always valid, adjust for it */
  1863.         col += p0len;
  1864.         count = p1len;
  1865.         if (p2 != 0)
  1866.         {
  1867.         /* p2 is valid, so remove it instead of p1 */
  1868.         col += p1len;
  1869.         count = p2len;
  1870.         }
  1871.         fixpos = 0;
  1872.     }
  1873.     }
  1874. #endif
  1875.  
  1876.     /*
  1877.      * When count is too big, reduce it.
  1878.      */
  1879.     movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
  1880.     if (movelen <= 1)
  1881.     {
  1882.     /*
  1883.      * If we just took off the last character of a non-blank line, and
  1884.      * fixpos is TRUE, we don't want to end up positioned at the NUL,
  1885.      * unless we are in virtual mode.
  1886.      */
  1887.     if (col > 0 && fixpos && !virtual_active())
  1888.     {
  1889.         --curwin->w_cursor.col;
  1890. #ifdef FEAT_MBYTE
  1891.         if (has_mbyte)
  1892.         curwin->w_cursor.col -=
  1893.                 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
  1894. #endif
  1895.     }
  1896.     count = oldlen - col;
  1897.     movelen = 1;
  1898.     }
  1899.  
  1900.     /*
  1901.      * If the old line has been allocated the deletion can be done in the
  1902.      * existing line. Otherwise a new line has to be allocated
  1903.      */
  1904.     was_alloced = ml_line_alloced();        /* check if oldp was allocated */
  1905.     if (was_alloced)
  1906.     newp = oldp;                /* use same allocated memory */
  1907.     else
  1908.     {                        /* need to allocated a new line */
  1909.     newp = alloc((unsigned)(oldlen + 1 - count));
  1910.     if (newp == NULL)
  1911.         return FAIL;
  1912.     mch_memmove(newp, oldp, (size_t)col);
  1913.     }
  1914.     mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
  1915.     if (!was_alloced)
  1916.     ml_replace(lnum, newp, FALSE);
  1917.  
  1918.     /* mark the buffer as changed and prepare for displaying */
  1919.     changed_bytes(lnum, curwin->w_cursor.col);
  1920.  
  1921.     return OK;
  1922. }
  1923.  
  1924. /*
  1925.  * Delete from cursor to end of line.
  1926.  * Caller must have prepared for undo.
  1927.  *
  1928.  * return FAIL for failure, OK otherwise
  1929.  */
  1930.     int
  1931. truncate_line(fixpos)
  1932.     int        fixpos;        /* if TRUE fix the cursor position when done */
  1933. {
  1934.     char_u    *newp;
  1935.     linenr_T    lnum = curwin->w_cursor.lnum;
  1936.     colnr_T    col = curwin->w_cursor.col;
  1937.  
  1938.     if (col == 0)
  1939.     newp = vim_strsave((char_u *)"");
  1940.     else
  1941.     newp = vim_strnsave(ml_get(lnum), col);
  1942.  
  1943.     if (newp == NULL)
  1944.     return FAIL;
  1945.  
  1946.     ml_replace(lnum, newp, FALSE);
  1947.  
  1948.     /* mark the buffer as changed and prepare for displaying */
  1949.     changed_bytes(lnum, curwin->w_cursor.col);
  1950.  
  1951.     /*
  1952.      * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
  1953.      */
  1954.     if (fixpos && curwin->w_cursor.col > 0)
  1955.     --curwin->w_cursor.col;
  1956.  
  1957.     return OK;
  1958. }
  1959.  
  1960. /*
  1961.  * Delete "nlines" lines at the cursor.
  1962.  * Saves the lines for undo first if "undo" is TRUE.
  1963.  */
  1964.     void
  1965. del_lines(nlines, undo)
  1966.     long    nlines;        /* number of lines to delete */
  1967.     int        undo;        /* if TRUE, prepare for undo */
  1968. {
  1969.     long    n;
  1970.  
  1971.     if (nlines <= 0)
  1972.     return;
  1973.  
  1974.     /* save the deleted lines for undo */
  1975.     if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
  1976.     return;
  1977.  
  1978.     for (n = 0; n < nlines; )
  1979.     {
  1980.     if (curbuf->b_ml.ml_flags & ML_EMPTY)        /* nothing to delete */
  1981.         break;
  1982.  
  1983.     ml_delete(curwin->w_cursor.lnum, TRUE);
  1984.     ++n;
  1985.  
  1986.     /* If we delete the last line in the file, stop */
  1987.     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
  1988.         break;
  1989.     }
  1990.     /* adjust marks, mark the buffer as changed and prepare for displaying */
  1991.     deleted_lines_mark(curwin->w_cursor.lnum, n);
  1992.  
  1993.     curwin->w_cursor.col = 0;
  1994.     check_cursor_lnum();
  1995. }
  1996.  
  1997.     int
  1998. gchar_pos(pos)
  1999.     pos_T *pos;
  2000. {
  2001.     char_u    *ptr = ml_get_pos(pos);
  2002.  
  2003. #ifdef FEAT_MBYTE
  2004.     if (has_mbyte)
  2005.     return (*mb_ptr2char)(ptr);
  2006. #endif
  2007.     return (int)*ptr;
  2008. }
  2009.  
  2010.     int
  2011. gchar_cursor()
  2012. {
  2013. #ifdef FEAT_MBYTE
  2014.     if (has_mbyte)
  2015.     return (*mb_ptr2char)(ml_get_cursor());
  2016. #endif
  2017.     return (int)*ml_get_cursor();
  2018. }
  2019.  
  2020. /*
  2021.  * Write a character at the current cursor position.
  2022.  * It is directly written into the block.
  2023.  */
  2024.     void
  2025. pchar_cursor(c)
  2026.     int c;
  2027. {
  2028.     *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
  2029.                           + curwin->w_cursor.col) = c;
  2030. }
  2031.  
  2032. #if 0 /* not used */
  2033. /*
  2034.  * Put *pos at end of current buffer
  2035.  */
  2036.     void
  2037. goto_endofbuf(pos)
  2038.     pos_T    *pos;
  2039. {
  2040.     char_u  *p;
  2041.  
  2042.     pos->lnum = curbuf->b_ml.ml_line_count;
  2043.     pos->col = 0;
  2044.     p = ml_get(pos->lnum);
  2045.     while (*p++)
  2046.     ++pos->col;
  2047. }
  2048. #endif
  2049.  
  2050. /*
  2051.  * When extra == 0: Return TRUE if the cursor is before or on the first
  2052.  *            non-blank in the line.
  2053.  * When extra == 1: Return TRUE if the cursor is before the first non-blank in
  2054.  *            the line.
  2055.  */
  2056.     int
  2057. inindent(extra)
  2058.     int        extra;
  2059. {
  2060.     char_u    *ptr;
  2061.     colnr_T    col;
  2062.  
  2063.     for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
  2064.     ++ptr;
  2065.     if (col >= curwin->w_cursor.col + extra)
  2066.     return TRUE;
  2067.     else
  2068.     return FALSE;
  2069. }
  2070.  
  2071. /*
  2072.  * Skip to next part of an option argument: Skip space and comma.
  2073.  */
  2074.     char_u *
  2075. skip_to_option_part(p)
  2076.     char_u  *p;
  2077. {
  2078.     if (*p == ',')
  2079.     ++p;
  2080.     while (*p == ' ')
  2081.     ++p;
  2082.     return p;
  2083. }
  2084.  
  2085. /*
  2086.  * changed() is called when something in the current buffer is changed.
  2087.  *
  2088.  * Most often called through changed_bytes() and changed_lines(), which also
  2089.  * mark the area of the display to be redrawn.
  2090.  */
  2091.     void
  2092. changed()
  2093. {
  2094.     int        save_msg_scroll = msg_scroll;
  2095.  
  2096.     if (!curbuf->b_changed)
  2097.     {
  2098.     change_warning(0);
  2099.     /* Create a swap file if that is wanted.
  2100.      * Don't do this for "nofile" and "nowrite" buffer types. */
  2101.     if (curbuf->b_may_swap
  2102. #ifdef FEAT_QUICKFIX
  2103.         && !bt_dontwrite(curbuf)
  2104. #endif
  2105.         )
  2106.     {
  2107.         ml_open_file(curbuf);
  2108.  
  2109.         /* The ml_open_file() can cause an ATTENTION message.
  2110.          * Wait two seconds, to make sure the user reads this unexpected
  2111.          * message.  Since we could be anywhere, call wait_return() now,
  2112.          * and don't let the emsg() set msg_scroll. */
  2113.         if (need_wait_return && emsg_silent == 0)
  2114.         {
  2115.         out_flush();
  2116.         ui_delay(2000L, TRUE);
  2117.         wait_return(TRUE);
  2118.         msg_scroll = save_msg_scroll;
  2119.         }
  2120.     }
  2121.     curbuf->b_changed = TRUE;
  2122.     ml_setdirty(curbuf, TRUE);
  2123. #ifdef FEAT_WINDOWS
  2124.     check_status(curbuf);
  2125. #endif
  2126. #ifdef FEAT_TITLE
  2127.     need_maketitle = TRUE;        /* set window title later */
  2128. #endif
  2129.     }
  2130.     ++curbuf->b_changedtick;
  2131.     ++global_changedtick;
  2132. }
  2133.  
  2134. static void changedOneline __ARGS((linenr_T lnum));
  2135. static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
  2136.  
  2137. /*
  2138.  * Changed bytes within a single line for the current buffer.
  2139.  * - marks the windows on this buffer to be redisplayed
  2140.  * - marks the buffer changed by calling changed()
  2141.  * - invalidates cached values
  2142.  */
  2143.     void
  2144. changed_bytes(lnum, col)
  2145.     linenr_T    lnum;
  2146.     colnr_T    col;
  2147. {
  2148.     changedOneline(lnum);
  2149.     changed_common(lnum, col, lnum + 1, 0L);
  2150. }
  2151.  
  2152.     static void
  2153. changedOneline(lnum)
  2154.     linenr_T    lnum;
  2155. {
  2156.     if (curbuf->b_mod_set)
  2157.     {
  2158.     /* find the maximum area that must be redisplayed */
  2159.     if (lnum < curbuf->b_mod_top)
  2160.         curbuf->b_mod_top = lnum;
  2161.     else if (lnum >= curbuf->b_mod_bot)
  2162.         curbuf->b_mod_bot = lnum + 1;
  2163.     }
  2164.     else
  2165.     {
  2166.     /* set the area that must be redisplayed to one line */
  2167.     curbuf->b_mod_set = TRUE;
  2168.     curbuf->b_mod_top = lnum;
  2169.     curbuf->b_mod_bot = lnum + 1;
  2170.     curbuf->b_mod_xlines = 0;
  2171.     }
  2172. }
  2173.  
  2174. /*
  2175.  * Appended "count" lines below line "lnum" in the current buffer.
  2176.  * Must be called AFTER the change and after mark_adjust().
  2177.  * Takes care of marking the buffer to be redrawn and sets the changed flag.
  2178.  */
  2179.     void
  2180. appended_lines(lnum, count)
  2181.     linenr_T    lnum;
  2182.     long    count;
  2183. {
  2184.     changed_lines(lnum + 1, 0, lnum + 1, count);
  2185. }
  2186.  
  2187. /*
  2188.  * Like appended_lines(), but adjust marks first.
  2189.  */
  2190.     void
  2191. appended_lines_mark(lnum, count)
  2192.     linenr_T    lnum;
  2193.     long    count;
  2194. {
  2195.     mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
  2196.     changed_lines(lnum + 1, 0, lnum + 1, count);
  2197. }
  2198.  
  2199. /*
  2200.  * Deleted "count" lines at line "lnum" in the current buffer.
  2201.  * Must be called AFTER the change and after mark_adjust().
  2202.  * Takes care of marking the buffer to be redrawn and sets the changed flag.
  2203.  */
  2204.     void
  2205. deleted_lines(lnum, count)
  2206.     linenr_T    lnum;
  2207.     long    count;
  2208. {
  2209.     changed_lines(lnum, 0, lnum + count, -count);
  2210. }
  2211.  
  2212. /*
  2213.  * Like deleted_lines(), but adjust marks first.
  2214.  */
  2215.     void
  2216. deleted_lines_mark(lnum, count)
  2217.     linenr_T    lnum;
  2218.     long    count;
  2219. {
  2220.     mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
  2221.     changed_lines(lnum, 0, lnum + count, -count);
  2222. }
  2223.  
  2224. /*
  2225.  * Changed lines for the current buffer.
  2226.  * Must be called AFTER the change and after mark_adjust().
  2227.  * - mark the buffer changed by calling changed()
  2228.  * - mark the windows on this buffer to be redisplayed
  2229.  * - invalidate cached values
  2230.  * "lnum" is the first line that needs displaying, "lnume" the first line
  2231.  * below the changed lines (BEFORE the change).
  2232.  * When only inserting lines, "lnum" and "lnume" are equal.
  2233.  * Takes care of calling changed() and updating b_mod_*.
  2234.  */
  2235.     void
  2236. changed_lines(lnum, col, lnume, xtra)
  2237.     linenr_T    lnum;        /* first line with change */
  2238.     colnr_T    col;        /* column in first line with change */
  2239.     linenr_T    lnume;        /* line below last changed line */
  2240.     long    xtra;        /* number of extra lines (negative when deleting) */
  2241. {
  2242.     if (curbuf->b_mod_set)
  2243.     {
  2244.     /* find the maximum area that must be redisplayed */
  2245.     if (lnum < curbuf->b_mod_top)
  2246.         curbuf->b_mod_top = lnum;
  2247.     if (lnum < curbuf->b_mod_bot)
  2248.     {
  2249.         /* adjust old bot position for xtra lines */
  2250.         curbuf->b_mod_bot += xtra;
  2251.         if (curbuf->b_mod_bot < lnum)
  2252.         curbuf->b_mod_bot = lnum;
  2253.     }
  2254.     if (lnume + xtra > curbuf->b_mod_bot)
  2255.         curbuf->b_mod_bot = lnume + xtra;
  2256.     curbuf->b_mod_xlines += xtra;
  2257.     }
  2258.     else
  2259.     {
  2260.     /* set the area that must be redisplayed */
  2261.     curbuf->b_mod_set = TRUE;
  2262.     curbuf->b_mod_top = lnum;
  2263.     curbuf->b_mod_bot = lnume + xtra;
  2264.     curbuf->b_mod_xlines = xtra;
  2265.     }
  2266.  
  2267.     changed_common(lnum, col, lnume, xtra);
  2268. }
  2269.  
  2270.     static void
  2271. changed_common(lnum, col, lnume, xtra)
  2272.     linenr_T    lnum;
  2273.     colnr_T    col;
  2274.     linenr_T    lnume;
  2275.     long    xtra;
  2276. {
  2277.     win_T    *wp;
  2278.     int        i;
  2279.  
  2280.     /* mark the buffer as modified */
  2281.     changed();
  2282.  
  2283.     /* set the '. mark */
  2284.     curbuf->b_last_change.lnum = lnum;
  2285.     curbuf->b_last_change.col = col;
  2286.  
  2287.     FOR_ALL_WINDOWS(wp)
  2288.     {
  2289.     if (wp->w_buffer == curbuf)
  2290.     {
  2291.         /* Mark this window to be redrawn later. */
  2292.         if (wp->w_redr_type < VALID)
  2293.         wp->w_redr_type = VALID;
  2294.  
  2295.         /* Check if a change in the buffer has invalidated the cached
  2296.          * values for the cursor. */
  2297. #ifdef FEAT_FOLDING
  2298.         /*
  2299.          * Update the folds for this window.  Can't postpone this, because
  2300.          * a following operator might work on the whole fold: ">>dd".
  2301.          */
  2302.         foldUpdate(wp, lnum, lnume + xtra - 1);
  2303.  
  2304.         /* The change may cause lines above or below the change to become
  2305.          * included in a fold.  Set lnum/lnume to the first/last line that
  2306.          * might be displayed differently. */
  2307.         hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
  2308.         hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
  2309.  
  2310.         /* If the changed line is in a range of previously folded lines,
  2311.          * compare with the first line in that range. */
  2312.         if (wp->w_cursor.lnum <= lnum)
  2313.         {
  2314.         i = find_wl_entry(wp, lnum);
  2315.         if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
  2316.             changed_line_abv_curs_win(wp);
  2317.         }
  2318. #endif
  2319.  
  2320.         if (wp->w_cursor.lnum > lnum)
  2321.         changed_line_abv_curs_win(wp);
  2322.         else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
  2323.         changed_cline_bef_curs_win(wp);
  2324.         if (wp->w_botline >= lnum)
  2325.         {
  2326.         /* Assume that botline doesn't change (inserted lines make
  2327.          * other lines scroll down below botline). */
  2328.         approximate_botline_win(wp);
  2329.         }
  2330.  
  2331.         /* Check if any w_lines[] entries have become invalid.
  2332.          * For entries below the change: Correct the lnums for
  2333.          * inserted/deleted lines.  Makes it possible to stop displaying
  2334.          * after the change. */
  2335.         for (i = 0; i < wp->w_lines_valid; ++i)
  2336.         if (wp->w_lines[i].wl_valid)
  2337.         {
  2338.             if (wp->w_lines[i].wl_lnum >= lnum)
  2339.             {
  2340.             if (wp->w_lines[i].wl_lnum < lnume)
  2341.             {
  2342.                 /* line included in change */
  2343.                 wp->w_lines[i].wl_valid = FALSE;
  2344.             }
  2345.             else if (xtra != 0)
  2346.             {
  2347.                 /* line below change */
  2348.                 wp->w_lines[i].wl_lnum += xtra;
  2349. #ifdef FEAT_FOLDING
  2350.                 wp->w_lines[i].wl_lastlnum += xtra;
  2351. #endif
  2352.             }
  2353.             }
  2354. #ifdef FEAT_FOLDING
  2355.             else if (wp->w_lines[i].wl_lastlnum >= lnum)
  2356.             {
  2357.             /* change somewhere inside this range of folded lines,
  2358.              * may need to be redrawn */
  2359.             wp->w_lines[i].wl_valid = FALSE;
  2360.             }
  2361. #endif
  2362.         }
  2363.     }
  2364.     }
  2365.  
  2366.     /* Call update_screen() later, which checks out what needs to be redrawn,
  2367.      * since it notices b_mod_set and then uses b_mod_*. */
  2368.     if (must_redraw < VALID)
  2369.     must_redraw = VALID;
  2370. }
  2371.  
  2372. /*
  2373.  * unchanged() is called when the changed flag must be reset for buffer 'buf'
  2374.  */
  2375.     void
  2376. unchanged(buf, ff)
  2377.     buf_T    *buf;
  2378.     int        ff;    /* also reset 'fileformat' */
  2379. {
  2380.     if (buf->b_changed || (ff && file_ff_differs(buf)))
  2381.     {
  2382.     buf->b_changed = 0;
  2383.     ml_setdirty(buf, FALSE);
  2384.     if (ff)
  2385.         save_file_ff(buf);
  2386. #ifdef FEAT_WINDOWS
  2387.     check_status(buf);
  2388. #endif
  2389. #ifdef FEAT_TITLE
  2390.     need_maketitle = TRUE;        /* set window title later */
  2391. #endif
  2392.     }
  2393.     ++buf->b_changedtick;
  2394.     ++global_changedtick;
  2395. }
  2396.  
  2397. #if defined(FEAT_WINDOWS) || defined(PROTO)
  2398. /*
  2399.  * check_status: called when the status bars for the buffer 'buf'
  2400.  *         need to be updated
  2401.  */
  2402.     void
  2403. check_status(buf)
  2404.     buf_T    *buf;
  2405. {
  2406.     win_T    *wp;
  2407.  
  2408.     for (wp = firstwin; wp != NULL; wp = wp->w_next)
  2409.     if (wp->w_buffer == buf && wp->w_status_height)
  2410.     {
  2411.         wp->w_redr_status = TRUE;
  2412.         if (must_redraw < VALID)
  2413.         must_redraw = VALID;
  2414.     }
  2415. }
  2416. #endif
  2417.  
  2418. /*
  2419.  * If the file is readonly, give a warning message with the first change.
  2420.  * Don't do this for autocommands.
  2421.  * Don't use emsg(), because it flushes the macro buffer.
  2422.  * If we have undone all changes b_changed will be FALSE, but b_did_warn
  2423.  * will be TRUE.
  2424.  */
  2425.     void
  2426. change_warning(col)
  2427.     int        col;        /* column for message; non-zero when in insert
  2428.                    mode and 'showmode' is on */
  2429. {
  2430.     if (curbuf->b_did_warn == FALSE
  2431.         && curbufIsChanged() == 0
  2432. #ifdef FEAT_AUTOCMD
  2433.         && !autocmd_busy
  2434. #endif
  2435.         && curbuf->b_p_ro)
  2436.     {
  2437. #ifdef FEAT_AUTOCMD
  2438.     apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
  2439.     if (!curbuf->b_p_ro)
  2440.         return;
  2441. #endif
  2442.     /*
  2443.      * Do what msg() does, but with a column offset if the warning should
  2444.      * be after the mode message.
  2445.      */
  2446.     msg_start();
  2447.     if (msg_row == Rows - 1)
  2448.         msg_col = col;
  2449.     MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
  2450.                            hl_attr(HLF_W) | MSG_HIST);
  2451.     msg_clr_eos();
  2452.     (void)msg_end();
  2453.     if (msg_silent == 0)
  2454.     {
  2455.         out_flush();
  2456.         ui_delay(1000L, TRUE); /* give the user time to think about it */
  2457.     }
  2458.     curbuf->b_did_warn = TRUE;
  2459.     redraw_cmdline = FALSE;    /* don't redraw and erase the message */
  2460.     if (msg_row < Rows - 1)
  2461.         showmode();
  2462.     }
  2463. }
  2464.  
  2465. /*
  2466.  * Ask for a reply from the user, a 'y' or a 'n'.
  2467.  * No other characters are accepted, the message is repeated until a valid
  2468.  * reply is entered or CTRL-C is hit.
  2469.  * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
  2470.  * from any buffers but directly from the user.
  2471.  *
  2472.  * return the 'y' or 'n'
  2473.  */
  2474.     int
  2475. ask_yesno(str, direct)
  2476.     char_u  *str;
  2477.     int        direct;
  2478. {
  2479.     int        r = ' ';
  2480.     int        save_State = State;
  2481.  
  2482.     if (exiting)        /* put terminal in raw mode for this question */
  2483.     settmode(TMODE_RAW);
  2484.     ++no_wait_return;
  2485. #ifdef USE_ON_FLY_SCROLL
  2486.     dont_scroll = TRUE;        /* disallow scrolling here */
  2487. #endif
  2488.     State = CONFIRM;        /* mouse behaves like with :confirm */
  2489. #ifdef FEAT_MOUSE
  2490.     setmouse();            /* disables mouse for xterm */
  2491. #endif
  2492.     ++no_mapping;
  2493.     ++allow_keys;        /* no mapping here, but recognize keys */
  2494.  
  2495.     while (r != 'y' && r != 'n')
  2496.     {
  2497.     /* same highlighting as for wait_return */
  2498.     smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
  2499.     if (direct)
  2500.         r = get_keystroke();
  2501.     else
  2502.         r = safe_vgetc();
  2503.     if (r == Ctrl_C || r == ESC)
  2504.         r = 'n';
  2505.     msg_putchar(r);        /* show what you typed */
  2506.     out_flush();
  2507.     }
  2508.     --no_wait_return;
  2509.     State = save_State;
  2510. #ifdef FEAT_MOUSE
  2511.     setmouse();
  2512. #endif
  2513.     --no_mapping;
  2514.     --allow_keys;
  2515.  
  2516.     return r;
  2517. }
  2518.  
  2519. /*
  2520.  * Get a key stroke directly from the user.
  2521.  * Ignores mouse clicks and scrollbar events.
  2522.  * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
  2523.  * Disadvantage: typeahead is ignored.
  2524.  * Translates the interrupt character for unix to ESC.
  2525.  */
  2526.     int
  2527. get_keystroke()
  2528. {
  2529. #define CBUFLEN 151
  2530.     char_u    buf[CBUFLEN];
  2531.     int        len = 0;
  2532.     int        n;
  2533.  
  2534.     for (;;)
  2535.     {
  2536.     cursor_on();
  2537.     out_flush();
  2538.  
  2539.     /* First time: blocking wait.  Second time: wait up to 100ms for a
  2540.      * terminal code to complete.  Leave some room for check_termcode() to
  2541.      * insert a key code into (max 5 chars plus NUL).  And
  2542.      * fix_input_buffer() can triple the number of bytes. */
  2543.     n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
  2544.                                len == 0 ? -1L : 100L);
  2545.     if (n > 0)
  2546.     {
  2547.         /* Replace zero and CSI by a special key code. */
  2548.         n = fix_input_buffer(buf + len, n, FALSE);
  2549.         len += n;
  2550.     }
  2551.  
  2552.     /* incomplete termcode: get more characters */
  2553.     if ((n = check_termcode(1, buf, len)) < 0)
  2554.         continue;
  2555.     /* found a termcode: adjust length */
  2556.     if (n > 0)
  2557.         len = n;
  2558.     if (len == 0)        /* nothing typed yet */
  2559.         continue;
  2560.  
  2561.     /* Handle modifier and/or special key code. */
  2562.     n = buf[0];
  2563.     if (n == K_SPECIAL)
  2564.     {
  2565.         n = TO_SPECIAL(buf[1], buf[2]);
  2566.         if (buf[1] == KS_MODIFIER
  2567.             || n == K_IGNORE
  2568. #ifdef FEAT_MOUSE
  2569.             || n == K_LEFTMOUSE
  2570.             || n == K_LEFTMOUSE_NM
  2571.             || n == K_LEFTDRAG
  2572.             || n ==  K_LEFTRELEASE
  2573.             || n ==  K_LEFTRELEASE_NM
  2574.             || n ==  K_MIDDLEMOUSE
  2575.             || n ==  K_MIDDLEDRAG
  2576.             || n ==  K_MIDDLERELEASE
  2577.             || n ==  K_RIGHTMOUSE
  2578.             || n ==  K_RIGHTDRAG
  2579.             || n ==  K_RIGHTRELEASE
  2580.             || n ==  K_MOUSEDOWN
  2581.             || n ==  K_MOUSEUP
  2582. # ifdef FEAT_GUI
  2583.             || n == K_VER_SCROLLBAR
  2584.             || n == K_HOR_SCROLLBAR
  2585. # endif
  2586. #endif
  2587.            )
  2588.         {
  2589.         if (buf[1] == KS_MODIFIER)
  2590.             mod_mask = buf[2];
  2591.         len -= 3;
  2592.         if (len > 0)
  2593.             mch_memmove(buf, buf + 3, (size_t)len);
  2594.         continue;
  2595.         }
  2596.     }
  2597. #ifdef UNIX
  2598.     if (n == intr_char)
  2599.         n = ESC;
  2600. #endif
  2601.     break;
  2602.     }
  2603.     return n;
  2604. }
  2605.  
  2606. /*
  2607.  * get a number from the user
  2608.  */
  2609.     int
  2610. get_number(colon)
  2611.     int    colon;            /* allow colon to abort */
  2612. {
  2613.     int    n = 0;
  2614.     int    c;
  2615.  
  2616.     /* When not printing messages, the user won't know what to type, return a
  2617.      * zero (as if CR was hit). */
  2618.     if (msg_silent != 0)
  2619.     return 0;
  2620.  
  2621. #ifdef USE_ON_FLY_SCROLL
  2622.     dont_scroll = TRUE;        /* disallow scrolling here */
  2623. #endif
  2624.     ++no_mapping;
  2625.     ++allow_keys;        /* no mapping here, but recognize keys */
  2626.     for (;;)
  2627.     {
  2628.     windgoto(msg_row, msg_col);
  2629.     c = safe_vgetc();
  2630.     if (vim_isdigit(c))
  2631.     {
  2632.         n = n * 10 + c - '0';
  2633.         msg_putchar(c);
  2634.     }
  2635.     else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
  2636.     {
  2637.         n /= 10;
  2638.         MSG_PUTS("\b \b");
  2639.     }
  2640.     else if (n == 0 && c == ':' && colon)
  2641.     {
  2642.         stuffcharReadbuff(':');
  2643.         if (!exmode_active)
  2644.         cmdline_row = msg_row;
  2645.         skip_redraw = TRUE;        /* skip redraw once */
  2646.         do_redraw = FALSE;
  2647.         break;
  2648.     }
  2649.     else if (c == CR || c == NL || c == Ctrl_C || c == ESC)
  2650.         break;
  2651.     }
  2652.     --no_mapping;
  2653.     --allow_keys;
  2654.     return n;
  2655. }
  2656.  
  2657.     void
  2658. msgmore(n)
  2659.     long n;
  2660. {
  2661.     long pn;
  2662.  
  2663.     if (global_busy        /* no messages now, wait until global is finished */
  2664.         || keep_msg != NULL /* there is a message already, skip this one */
  2665.         || !messaging())  /* 'lazyredraw' set, don't do messages now */
  2666.     return;
  2667.  
  2668.     if (n > 0)
  2669.     pn = n;
  2670.     else
  2671.     pn = -n;
  2672.  
  2673.     if (pn > p_report)
  2674.     {
  2675.     if (pn == 1)
  2676.     {
  2677.         if (n > 0)
  2678.         STRCPY(msg_buf, _("1 more line"));
  2679.         else
  2680.         STRCPY(msg_buf, _("1 line less"));
  2681.     }
  2682.     else
  2683.     {
  2684.         if (n > 0)
  2685.         sprintf((char *)msg_buf, _("%ld more lines"), pn);
  2686.         else
  2687.         sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
  2688.     }
  2689.     if (got_int)
  2690.         STRCAT(msg_buf, _(" (Interrupted)"));
  2691.     if (msg(msg_buf))
  2692.     {
  2693.         set_keep_msg(msg_buf);
  2694.         keep_msg_attr = 0;
  2695.     }
  2696.     }
  2697. }
  2698.  
  2699. /*
  2700.  * flush map and typeahead buffers and give a warning for an error
  2701.  */
  2702.     void
  2703. beep_flush()
  2704. {
  2705.     if (emsg_silent == 0)
  2706.     {
  2707.     flush_buffers(FALSE);
  2708.     vim_beep();
  2709.     }
  2710. }
  2711.  
  2712. /*
  2713.  * give a warning for an error
  2714.  */
  2715.     void
  2716. vim_beep()
  2717. {
  2718.     if (emsg_silent == 0)
  2719.     {
  2720.     if (p_vb)
  2721.     {
  2722.         out_str(T_VB);
  2723.     }
  2724.     else
  2725.     {
  2726. #ifdef MSDOS
  2727.         /*
  2728.          * The number of beeps outputted is reduced to avoid having to wait
  2729.          * for all the beeps to finish. This is only a problem on systems
  2730.          * where the beeps don't overlap.
  2731.          */
  2732.         if (beep_count == 0 || beep_count == 10)
  2733.         {
  2734.         out_char(BELL);
  2735.         beep_count = 1;
  2736.         }
  2737.         else
  2738.         ++beep_count;
  2739. #else
  2740.         out_char(BELL);
  2741. #endif
  2742.     }
  2743.     }
  2744. }
  2745.  
  2746. /*
  2747.  * To get the "real" home directory:
  2748.  * - get value of $HOME
  2749.  * For Unix:
  2750.  *  - go to that directory
  2751.  *  - do mch_dirname() to get the real name of that directory.
  2752.  *  This also works with mounts and links.
  2753.  *  Don't do this for MS-DOS, it will change the "current dir" for a drive.
  2754.  */
  2755. static char_u    *homedir = NULL;
  2756.  
  2757.     void
  2758. init_homedir()
  2759. {
  2760.     char_u  *var;
  2761.  
  2762. #ifdef VMS
  2763.     var = mch_getenv((char_u *)"SYS$LOGIN");
  2764. #else
  2765.     var = mch_getenv((char_u *)"HOME");
  2766. #endif
  2767.  
  2768.     if (var != NULL && *var == NUL)    /* empty is same as not set */
  2769.     var = NULL;
  2770.  
  2771. #ifdef WIN3264
  2772.     /*
  2773.      * Typically, $HOME is not defined on Windows, unless the user has
  2774.      * specifically defined it for Vim's sake.  However, on Windows NT
  2775.      * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
  2776.      * each user.  Try constructing $HOME from these.
  2777.      */
  2778.     if (var == NULL)
  2779.     {
  2780.     char_u *homedrive, *homepath;
  2781.  
  2782.     homedrive = mch_getenv((char_u *)"HOMEDRIVE");
  2783.     homepath = mch_getenv((char_u *)"HOMEPATH");
  2784.     if (homedrive != NULL && homepath != NULL)
  2785.     {
  2786.         sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
  2787.         if (NameBuff[0] != NUL)
  2788.         var = NameBuff;
  2789.     }
  2790.     }
  2791. #endif
  2792.  
  2793. #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
  2794.     /*
  2795.      * Default home dir is C:/
  2796.      * Best assumption we can make in such a situation.
  2797.      */
  2798.     if (var == NULL)
  2799.     var = "C:/";
  2800. #endif
  2801.     if (var != NULL)
  2802.     {
  2803. #ifdef UNIX
  2804.     /*
  2805.      * Change to the directory and get the actual path.  This resolves
  2806.      * links.
  2807.      */
  2808.     if (mch_dirname(NameBuff, MAXPATHL) == OK)
  2809.     {
  2810.         if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
  2811.         var = IObuff;
  2812.         mch_chdir((char *)NameBuff);
  2813.     }
  2814. #endif
  2815.     homedir = vim_strsave(var);
  2816.     }
  2817. }
  2818.  
  2819. /*
  2820.  * Expand environment variable with path name.
  2821.  * "~/" is also expanded, using $HOME.    For Unix "~user/" is expanded.
  2822.  * Skips over "\ ", "\~" and "\$".
  2823.  * If anything fails no expansion is done and dst equals src.
  2824.  */
  2825.     void
  2826. expand_env(src, dst, dstlen)
  2827.     char_u    *src;        /* input string e.g. "$HOME/vim.hlp" */
  2828.     char_u    *dst;        /* where to put the result */
  2829.     int        dstlen;        /* maximum length of the result */
  2830. {
  2831.     char_u    *tail;
  2832.     int        c;
  2833.     char_u    *var;
  2834.     int        copy_char;
  2835.     int        mustfree;    /* var was allocated, need to free it later */
  2836.     int        at_start = TRUE; /* at start of a name */
  2837.  
  2838.     src = skipwhite(src);
  2839.     --dstlen;            /* leave one char space for "\," */
  2840.     while (*src && dstlen > 0)
  2841.     {
  2842.     copy_char = TRUE;
  2843.     if (*src == '$'
  2844. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  2845.         || *src == '%'
  2846. #endif
  2847.         || (*src == '~' && at_start))
  2848.     {
  2849.         mustfree = FALSE;
  2850.  
  2851.         /*
  2852.          * The variable name is copied into dst temporarily, because it may
  2853.          * be a string in read-only memory and a NUL needs to be appended.
  2854.          */
  2855.         if (*src != '~')                /* environment var */
  2856.         {
  2857.         tail = src + 1;
  2858.         var = dst;
  2859.         c = dstlen - 1;
  2860.  
  2861. #ifdef UNIX
  2862.         /* Unix has ${var-name} type environment vars */
  2863.         if (*tail == '{' && !vim_isIDc('{'))
  2864.         {
  2865.             tail++;    /* ignore '{' */
  2866.             while (c-- > 0 && *tail && *tail != '}')
  2867.             *var++ = *tail++;
  2868.         }
  2869.         else
  2870. #endif
  2871.         {
  2872.             while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
  2873. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  2874.                 || (*src == '%' && *tail != '%')
  2875. #endif
  2876.                 ))
  2877.             {
  2878. #ifdef OS2        /* env vars only in uppercase */
  2879.             *var++ = TO_UPPER(*tail);
  2880.             tail++;        /* toupper() may be a macro! */
  2881. #else
  2882.             *var++ = *tail++;
  2883. #endif
  2884.             }
  2885.         }
  2886.  
  2887. #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
  2888. # ifdef UNIX
  2889.         if (src[1] == '{' && *tail != '}')
  2890. # else
  2891.         if (*src == '%' && *tail != '%')
  2892. # endif
  2893.             var = NULL;
  2894.         else
  2895.         {
  2896. # ifdef UNIX
  2897.             if (src[1] == '{')
  2898. # else
  2899.             if (*src == '%')
  2900. #endif
  2901.             ++tail;
  2902. #endif
  2903.             *var = NUL;
  2904.             var = vim_getenv(dst, &mustfree);
  2905. #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
  2906.         }
  2907. #endif
  2908.         }
  2909.                             /* home directory */
  2910.         else if (  src[1] == NUL
  2911.             || vim_ispathsep(src[1])
  2912.             || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
  2913.         {
  2914.         var = homedir;
  2915.         tail = src + 1;
  2916.         }
  2917.         else                    /* user directory */
  2918.         {
  2919. #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
  2920.         /*
  2921.          * Copy ~user to dst[], so we can put a NUL after it.
  2922.          */
  2923.         tail = src;
  2924.         var = dst;
  2925.         c = dstlen - 1;
  2926.         while (       c-- > 0
  2927.             && *tail
  2928.             && vim_isfilec(*tail)
  2929.             && !vim_ispathsep(*tail))
  2930.             *var++ = *tail++;
  2931.         *var = NUL;
  2932. # ifdef UNIX
  2933.         /*
  2934.          * If the system supports getpwnam(), use it.
  2935.          * Otherwise, or if getpwnam() fails, the shell is used to
  2936.          * expand ~user.  This is slower and may fail if the shell
  2937.          * does not support ~user (old versions of /bin/sh).
  2938.          */
  2939. #  if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
  2940.         {
  2941.             struct passwd *pw;
  2942.  
  2943.             pw = getpwnam((char *)dst + 1);
  2944.             if (pw != NULL)
  2945.             var = (char_u *)pw->pw_dir;
  2946.             else
  2947.             var = NULL;
  2948.         }
  2949.         if (var == NULL)
  2950. #  endif
  2951.         {
  2952.             expand_T    xpc;
  2953.  
  2954.             xpc.xp_context = EXPAND_FILES;
  2955.             var = ExpandOne(&xpc, dst, NULL,
  2956.                 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
  2957.             mustfree = TRUE;
  2958.         }
  2959.  
  2960. # else    /* !UNIX, thus VMS */
  2961.         /*
  2962.          * USER_HOME is a comma-separated list of
  2963.          * directories to search for the user account in.
  2964.          */
  2965.         {
  2966.             char_u    test[MAXPATHL], paths[MAXPATHL];
  2967.             char_u    *path, *next_path, *ptr;
  2968.             struct stat    st;
  2969.  
  2970.             STRCPY(paths, USER_HOME);
  2971.             next_path = paths;
  2972.             while (*next_path)
  2973.             {
  2974.             for (path = next_path; *next_path && *next_path != ',';
  2975.                 next_path++);
  2976.             if (*next_path)
  2977.                 *next_path++ = NUL;
  2978.             STRCPY(test, path);
  2979.             STRCAT(test, "/");
  2980.             STRCAT(test, dst + 1);
  2981.             if (mch_stat(test, &st) == 0)
  2982.             {
  2983.                 var = alloc(STRLEN(test) + 1);
  2984.                 STRCPY(var, test);
  2985.                 mustfree = TRUE;
  2986.                 break;
  2987.             }
  2988.             }
  2989.         }
  2990. # endif /* UNIX */
  2991. #else
  2992.         /* cannot expand user's home directory, so don't try */
  2993.         var = NULL;
  2994.         tail = (char_u *)"";    /* for gcc */
  2995. #endif /* UNIX || VMS */
  2996.         }
  2997.  
  2998.         if (var != NULL && *var != NUL
  2999.             && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
  3000.         {
  3001.         STRCPY(dst, var);
  3002.         dstlen -= (int)STRLEN(var);
  3003.         dst += STRLEN(var);
  3004.         /* if var[] ends in a path separator and tail[] starts
  3005.          * with it, skip a character */
  3006.         if (*var != NUL && vim_ispathsep(dst[-1])
  3007. #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
  3008.             && dst[-1] != ':'
  3009. #endif
  3010.             && vim_ispathsep(*tail))
  3011.             ++tail;
  3012.         src = tail;
  3013.         copy_char = FALSE;
  3014.         }
  3015.         if (mustfree)
  3016.         vim_free(var);
  3017.     }
  3018.  
  3019.     if (copy_char)        /* copy at least one char */
  3020.     {
  3021.         /*
  3022.          * Recogize the start of a new name, for '~'.
  3023.          */
  3024.         at_start = FALSE;
  3025.         if (src[0] == '\\')
  3026.         {
  3027.         *dst++ = *src++;
  3028.         --dstlen;
  3029.         }
  3030.         else if (src[0] == ' ' || src[0] == ',')
  3031.         at_start = TRUE;
  3032.         *dst++ = *src++;
  3033.         --dstlen;
  3034.     }
  3035.     }
  3036.     *dst = NUL;
  3037. }
  3038.  
  3039. /*
  3040.  * Vim's version of getenv().
  3041.  * Special handling of $HOME, $VIM and $VIMRUNTIME.
  3042.  */
  3043.     char_u *
  3044. vim_getenv(name, mustfree)
  3045.     char_u    *name;
  3046.     int        *mustfree;    /* set to TRUE when returned is allocated */
  3047. {
  3048.     char_u    *p;
  3049.     char_u    *pend;
  3050.     int        vimruntime;
  3051.  
  3052. #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
  3053.     /* use "C:/" when $HOME is not set */
  3054.     if (STRCMP(name, "HOME") == 0)
  3055.     return homedir;
  3056. #endif
  3057.  
  3058.     p = mch_getenv(name);
  3059.     if (p != NULL && *p == NUL)        /* empty is the same as not set */
  3060.     p = NULL;
  3061.  
  3062.     if (p != NULL)
  3063.     return p;
  3064.  
  3065.     vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
  3066.     if (!vimruntime && STRCMP(name, "VIM") != 0)
  3067.     return NULL;
  3068.  
  3069.     /*
  3070.      * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
  3071.      * Don't do this when default_vimruntime_dir is non-empty.
  3072.      */
  3073.     if (vimruntime
  3074. #ifdef HAVE_PATHDEF
  3075.         && *default_vimruntime_dir == NUL
  3076. #endif
  3077.        )
  3078.     {
  3079.     p = mch_getenv((char_u *)"VIM");
  3080.     if (p != NULL && *p == NUL)        /* empty is the same as not set */
  3081.         p = NULL;
  3082.     if (p != NULL)
  3083.     {
  3084.         p = vim_version_dir(p);
  3085.         if (p != NULL)
  3086.         *mustfree = TRUE;
  3087.         else
  3088.         p = mch_getenv((char_u *)"VIM");
  3089.     }
  3090.     }
  3091.  
  3092.     /*
  3093.      * When expanding $VIM or $VIMRUNTIME fails, try using:
  3094.      * - the directory name from 'helpfile' (unless it contains '$')
  3095.      * - the executable name from argv[0]
  3096.      */
  3097.     if (p == NULL)
  3098.     {
  3099.     if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
  3100.         p = p_hf;
  3101. #ifdef USE_EXE_NAME
  3102.     /*
  3103.      * Use the name of the executable, obtained from argv[0].
  3104.      */
  3105.     else
  3106.         p = exe_name;
  3107. #endif
  3108.     if (p != NULL)
  3109.     {
  3110.         /* remove the file name */
  3111.         pend = gettail(p);
  3112.  
  3113.         /* remove "doc/" from 'helpfile', if present */
  3114.         if (p == p_hf)
  3115.         pend = remove_tail(p, pend, (char_u *)"doc");
  3116.  
  3117. #ifdef USE_EXE_NAME
  3118. # ifdef MACOS_X
  3119.         /* remove "build/..." from exe_name, if present */
  3120.         if (p == exe_name)
  3121.         {
  3122.         pend = remove_tail(p, pend, (char_u *)"Contents/MacOS");
  3123.         pend = remove_tail_with_ext(p, pend, (char_u *)".app");
  3124.         pend = remove_tail(p, pend, (char_u *)"build");
  3125.         }
  3126. # endif
  3127.         /* remove "src/" from exe_name, if present */
  3128.         if (p == exe_name)
  3129.         pend = remove_tail(p, pend, (char_u *)"src");
  3130. #endif
  3131.  
  3132.         /* for $VIM, remove "runtime/" or "vim54/", if present */
  3133.         if (!vimruntime)
  3134.         {
  3135.         pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
  3136.         pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
  3137.         }
  3138.  
  3139.         /* remove trailing path separator */
  3140. #ifndef MACOS_CLASSIC
  3141.         /* With MacOS path (with  colons) the final colon is required */
  3142.         /* to avoid confusion between absoulute and relative path */
  3143.         if (pend > p && vim_ispathsep(*(pend - 1)))
  3144.         --pend;
  3145. #endif
  3146.  
  3147.         /* check that the result is a directory name */
  3148.         p = vim_strnsave(p, (int)(pend - p));
  3149.  
  3150.         if (p != NULL && !mch_isdir(p))
  3151.         {
  3152.         vim_free(p);
  3153.         p = NULL;
  3154.         }
  3155.         else
  3156.         {
  3157. #ifdef USE_EXE_NAME
  3158.         /* may add "/vim54" or "/runtime" if it exists */
  3159.         if (vimruntime && (pend = vim_version_dir(p)) != NULL)
  3160.         {
  3161.             vim_free(p);
  3162.             p = pend;
  3163.         }
  3164. #endif
  3165.         *mustfree = TRUE;
  3166.         }
  3167.     }
  3168.     }
  3169.  
  3170. #ifdef HAVE_PATHDEF
  3171.     /* When there is a pathdef.c file we can use default_vim_dir and
  3172.      * default_vimruntime_dir */
  3173.     if (p == NULL)
  3174.     {
  3175.     /* Only use default_vimruntime_dir when it is not empty */
  3176.     if (vimruntime && *default_vimruntime_dir != NUL)
  3177.     {
  3178.         p = default_vimruntime_dir;
  3179.         *mustfree = FALSE;
  3180.     }
  3181.     else if (*default_vim_dir != NUL)
  3182.     {
  3183.         if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
  3184.         *mustfree = TRUE;
  3185.         else
  3186.         {
  3187.         p = default_vim_dir;
  3188.         *mustfree = FALSE;
  3189.         }
  3190.     }
  3191.     }
  3192. #endif
  3193.  
  3194.     /*
  3195.      * Set the environment variable, so that the new value can be found fast
  3196.      * next time, and others can also use it (e.g. Perl).
  3197.      */
  3198.     if (p != NULL)
  3199.     {
  3200.     if (vimruntime)
  3201.     {
  3202.         vim_setenv((char_u *)"VIMRUNTIME", p);
  3203.         didset_vimruntime = TRUE;
  3204. #ifdef FEAT_GETTEXT
  3205.         {
  3206.         char_u    *buf = alloc((unsigned int)STRLEN(p) + 6);
  3207.  
  3208.         if (buf != NULL)
  3209.         {
  3210.             STRCPY(buf, p);
  3211.             STRCAT(buf, "/lang");
  3212.             bindtextdomain(VIMPACKAGE, (char *)buf);
  3213.             vim_free(buf);
  3214.         }
  3215.         }
  3216. #endif
  3217.     }
  3218.     else
  3219.     {
  3220.         vim_setenv((char_u *)"VIM", p);
  3221.         didset_vim = TRUE;
  3222.     }
  3223.     }
  3224.     return p;
  3225. }
  3226.  
  3227. /*
  3228.  * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
  3229.  * Return NULL if not, return its name in allocated memory otherwise.
  3230.  */
  3231.     static char_u *
  3232. vim_version_dir(vimdir)
  3233.     char_u    *vimdir;
  3234. {
  3235.     char_u    *p;
  3236.  
  3237.     if (vimdir == NULL || *vimdir == NUL)
  3238.     return NULL;
  3239.     p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
  3240.     if (p != NULL && mch_isdir(p))
  3241.     return p;
  3242.     vim_free(p);
  3243.     p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
  3244.     if (p != NULL && mch_isdir(p))
  3245.     return p;
  3246.     vim_free(p);
  3247.     return NULL;
  3248. }
  3249.  
  3250. /*
  3251.  * If the string between "p" and "pend" ends in "name/", return "pend" minus
  3252.  * the length of "name/".  Otherwise return "pend".
  3253.  */
  3254.     static char_u *
  3255. remove_tail(p, pend, name)
  3256.     char_u    *p;
  3257.     char_u    *pend;
  3258.     char_u    *name;
  3259. {
  3260.     int        len = (int)STRLEN(name) + 1;
  3261.     char_u    *newend = pend - len;
  3262.  
  3263.     if (newend >= p
  3264.         && fnamencmp(newend, name, len - 1) == 0
  3265.         && (newend == p || vim_ispathsep(*(newend - 1))))
  3266.     return newend;
  3267.     return pend;
  3268. }
  3269.  
  3270. #if defined(USE_EXE_NAME) && defined(MACOS_X)
  3271. /*
  3272.  * If the string between "p" and "pend" ends in "???.ext/", return "pend" minus
  3273.  * the length of "???.ext/".  Otherwise return "pend".
  3274.  */
  3275.     static char_u *
  3276. remove_tail_with_ext(p, pend, ext)
  3277.     char_u    *p;
  3278.     char_u    *pend;
  3279.     char_u    *ext;
  3280. {
  3281.     int        len = (int)STRLEN(ext) + 1;
  3282.     char_u    *newend = pend - len;
  3283.  
  3284.     if (newend >= p
  3285.         && fnamencmp(newend, ext, len - 1) == 0)
  3286.     for (;newend != p && !vim_ispathsep(*(newend -1)); newend--);
  3287.  
  3288.     if (newend == p || vim_ispathsep(*(newend - 1)))
  3289.     return newend;
  3290.     return pend;
  3291. }
  3292. #endif
  3293.  
  3294. /*
  3295.  * Call expand_env() and store the result in an allocated string.
  3296.  * This is not very memory efficient, this expects the result to be freed
  3297.  * again soon.
  3298.  */
  3299.     char_u *
  3300. expand_env_save(src)
  3301.     char_u    *src;
  3302. {
  3303.     char_u    *p;
  3304.  
  3305.     p = alloc(MAXPATHL);
  3306.     if (p != NULL)
  3307.     expand_env(src, p, MAXPATHL);
  3308.     return p;
  3309. }
  3310.  
  3311. /*
  3312.  * Our portable version of setenv.
  3313.  */
  3314.     void
  3315. vim_setenv(name, val)
  3316.     char_u    *name;
  3317.     char_u    *val;
  3318. {
  3319. #ifdef HAVE_SETENV
  3320.     mch_setenv((char *)name, (char *)val, 1);
  3321. #else
  3322.     char_u    *envbuf;
  3323.  
  3324.     /*
  3325.      * Putenv does not copy the string, it has to remain
  3326.      * valid.  The allocated memory will never be freed.
  3327.      */
  3328.     envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
  3329.     if (envbuf != NULL)
  3330.     {
  3331.     sprintf((char *)envbuf, "%s=%s", name, val);
  3332.     putenv((char *)envbuf);
  3333.     }
  3334. #endif
  3335. }
  3336.  
  3337. #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
  3338. /*
  3339.  * Function given to ExpandGeneric() to obtain an environment variable name.
  3340.  */
  3341. /*ARGSUSED*/
  3342.     char_u *
  3343. get_env_name(xp, idx)
  3344.     expand_T    *xp;
  3345.     int        idx;
  3346. {
  3347. # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
  3348.     /*
  3349.      * No environ[] on the Amiga and on the Mac (using MPW).
  3350.      */
  3351.     return NULL;
  3352. # else
  3353. # ifndef __WIN32__
  3354.     /* Borland C++ 5.2 has this in a header file. */
  3355.     extern char        **environ;
  3356. # endif
  3357.     static char_u    name[100];
  3358.     char_u        *str;
  3359.     int            n;
  3360.  
  3361.     str = (char_u *)environ[idx];
  3362.     if (str == NULL)
  3363.     return NULL;
  3364.  
  3365.     for (n = 0; n < 99; ++n)
  3366.     {
  3367.     if (str[n] == '=' || str[n] == NUL)
  3368.         break;
  3369.     name[n] = str[n];
  3370.     }
  3371.     name[n] = NUL;
  3372.     return name;
  3373. # endif
  3374. }
  3375. #endif
  3376.  
  3377. /*
  3378.  * Replace home directory by "~" in each space or comma separated file name in
  3379.  * 'src'.
  3380.  * If anything fails (except when out of space) dst equals src.
  3381.  */
  3382.     void
  3383. home_replace(buf, src, dst, dstlen, one)
  3384.     buf_T    *buf;    /* when not NULL, check for help files */
  3385.     char_u    *src;    /* input file name */
  3386.     char_u    *dst;    /* where to put the result */
  3387.     int        dstlen;    /* maximum length of the result */
  3388.     int        one;    /* if TRUE, only replace one file name, include
  3389.                spaces and commas in the file name. */
  3390. {
  3391.     size_t    dirlen = 0, envlen = 0;
  3392.     size_t    len;
  3393.     char_u    *homedir_env;
  3394.     char_u    *p;
  3395.  
  3396.     if (src == NULL)
  3397.     {
  3398.     *dst = NUL;
  3399.     return;
  3400.     }
  3401.  
  3402.     /*
  3403.      * If the file is a help file, remove the path completely.
  3404.      */
  3405.     if (buf != NULL && buf->b_help)
  3406.     {
  3407.     STRCPY(dst, gettail(src));
  3408.     return;
  3409.     }
  3410.  
  3411.     /*
  3412.      * We check both the value of the $HOME environment variable and the
  3413.      * "real" home directory.
  3414.      */
  3415.     if (homedir != NULL)
  3416.     dirlen = STRLEN(homedir);
  3417.  
  3418. #ifdef VMS
  3419.     homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
  3420. #else
  3421.     homedir_env = mch_getenv((char_u *)"HOME");
  3422. #endif
  3423.  
  3424.     if (homedir_env != NULL && *homedir_env == NUL)
  3425.     homedir_env = NULL;
  3426.     if (homedir_env != NULL)
  3427.     envlen = STRLEN(homedir_env);
  3428.  
  3429.     if (!one)
  3430.     src = skipwhite(src);
  3431.     while (*src && dstlen > 0)
  3432.     {
  3433.     /*
  3434.      * Here we are at the beginning of a file name.
  3435.      * First, check to see if the beginning of the file name matches
  3436.      * $HOME or the "real" home directory. Check that there is a '/'
  3437.      * after the match (so that if e.g. the file is "/home/pieter/bla",
  3438.      * and the home directory is "/home/piet", the file does not end up
  3439.      * as "~er/bla" (which would seem to indicate the file "bla" in user
  3440.      * er's home directory)).
  3441.      */
  3442.     p = homedir;
  3443.     len = dirlen;
  3444.     for (;;)
  3445.     {
  3446.         if (   len
  3447.         && fnamencmp(src, p, len) == 0
  3448.         && (vim_ispathsep(src[len])
  3449.             || (!one && (src[len] == ',' || src[len] == ' '))
  3450.             || src[len] == NUL))
  3451.         {
  3452.         src += len;
  3453.         if (--dstlen > 0)
  3454.             *dst++ = '~';
  3455.  
  3456.         /*
  3457.          * If it's just the home directory, add  "/".
  3458.          */
  3459.         if (!vim_ispathsep(src[0]) && --dstlen > 0)
  3460.             *dst++ = '/';
  3461.         break;
  3462.         }
  3463.         if (p == homedir_env)
  3464.         break;
  3465.         p = homedir_env;
  3466.         len = envlen;
  3467.     }
  3468.  
  3469.     /* if (!one) skip to separator: space or comma */
  3470.     while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
  3471.         *dst++ = *src++;
  3472.     /* skip separator */
  3473.     while ((*src == ' ' || *src == ',') && --dstlen > 0)
  3474.         *dst++ = *src++;
  3475.     }
  3476.     /* if (dstlen == 0) out of space, what to do??? */
  3477.  
  3478.     *dst = NUL;
  3479. }
  3480.  
  3481. /*
  3482.  * Like home_replace, store the replaced string in allocated memory.
  3483.  * When something fails, NULL is returned.
  3484.  */
  3485.     char_u  *
  3486. home_replace_save(buf, src)
  3487.     buf_T    *buf;    /* when not NULL, check for help files */
  3488.     char_u    *src;    /* input file name */
  3489. {
  3490.     char_u    *dst;
  3491.     unsigned    len;
  3492.  
  3493.     len = 3;            /* space for "~/" and trailing NUL */
  3494.     if (src != NULL)        /* just in case */
  3495.     len += (unsigned)STRLEN(src);
  3496.     dst = alloc(len);
  3497.     if (dst != NULL)
  3498.     home_replace(buf, src, dst, len, TRUE);
  3499.     return dst;
  3500. }
  3501.  
  3502. /*
  3503.  * Compare two file names and return:
  3504.  * FPC_SAME   if they both exist and are the same file.
  3505.  * FPC_SAMEX  if they both don't exist and have the same file name.
  3506.  * FPC_DIFF   if they both exist and are different files.
  3507.  * FPC_NOTX   if they both don't exist.
  3508.  * FPC_DIFFX  if one of them doesn't exist.
  3509.  * For the first name environment variables are expanded
  3510.  */
  3511.     int
  3512. fullpathcmp(s1, s2, checkname)
  3513.     char_u *s1, *s2;
  3514.     int        checkname;        /* when both don't exist, check file names */
  3515. {
  3516. #ifdef UNIX
  3517.     char_u        exp1[MAXPATHL];
  3518.     char_u        full1[MAXPATHL];
  3519.     char_u        full2[MAXPATHL];
  3520.     struct stat        st1, st2;
  3521.     int            r1, r2;
  3522.  
  3523.     expand_env(s1, exp1, MAXPATHL);
  3524.     r1 = mch_stat((char *)exp1, &st1);
  3525.     r2 = mch_stat((char *)s2, &st2);
  3526.     if (r1 != 0 && r2 != 0)
  3527.     {
  3528.     /* if mch_stat() doesn't work, may compare the names */
  3529.     if (checkname)
  3530.     {
  3531.         if (fnamecmp(exp1, s2) == 0)
  3532.         return FPC_SAMEX;
  3533.         r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
  3534.         r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
  3535.         if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
  3536.         return FPC_SAMEX;
  3537.     }
  3538.     return FPC_NOTX;
  3539.     }
  3540.     if (r1 != 0 || r2 != 0)
  3541.     return FPC_DIFFX;
  3542.     if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
  3543.     return FPC_SAME;
  3544.     return FPC_DIFF;
  3545. #else
  3546.     char_u  *exp1;        /* expanded s1 */
  3547.     char_u  *full1;        /* full path of s1 */
  3548.     char_u  *full2;        /* full path of s2 */
  3549.     int        retval = FPC_DIFF;
  3550.     int        r1, r2;
  3551.  
  3552.     /* allocate one buffer to store three paths (alloc()/free() is slow!) */
  3553.     if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
  3554.     {
  3555.     full1 = exp1 + MAXPATHL;
  3556.     full2 = full1 + MAXPATHL;
  3557.  
  3558.     expand_env(s1, exp1, MAXPATHL);
  3559.     r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
  3560.     r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
  3561.  
  3562.     /* If vim_FullName() fails, the file probably doesn't exist. */
  3563.     if (r1 != OK && r2 != OK)
  3564.     {
  3565.         if (checkname && fnamecmp(exp1, s2) == 0)
  3566.         retval = FPC_SAMEX;
  3567.         else
  3568.         retval = FPC_NOTX;
  3569.     }
  3570.     else if (r1 != OK || r2 != OK)
  3571.         retval = FPC_DIFFX;
  3572.     else if (fnamecmp(full1, full2))
  3573.         retval = FPC_DIFF;
  3574.     else
  3575.         retval = FPC_SAME;
  3576.     vim_free(exp1);
  3577.     }
  3578.     return retval;
  3579. #endif
  3580. }
  3581.  
  3582. /*
  3583.  * get the tail of a path: the file name.
  3584.  */
  3585.     char_u *
  3586. gettail(fname)
  3587.     char_u *fname;
  3588. {
  3589.     char_u  *p1, *p2;
  3590.  
  3591.     if (fname == NULL)
  3592.     return (char_u *)"";
  3593.     for (p1 = p2 = fname; *p2; )    /* find last part of path */
  3594.     {
  3595.     if (vim_ispathsep(*p2))
  3596.         p1 = p2 + 1;
  3597. #ifdef FEAT_MBYTE
  3598.     if (has_mbyte)
  3599.         p2 += (*mb_ptr2len_check)(p2);
  3600.     else
  3601. #endif
  3602.         ++p2;
  3603.     }
  3604.     return p1;
  3605. }
  3606.  
  3607. /*
  3608.  * get the next path component (just after the next path separator).
  3609.  */
  3610.     char_u *
  3611. getnextcomp(fname)
  3612.     char_u *fname;
  3613. {
  3614.     while (*fname && !vim_ispathsep(*fname))
  3615.     ++fname;
  3616.     if (*fname)
  3617.     ++fname;
  3618.     return fname;
  3619. }
  3620.  
  3621. /*
  3622.  * Get a pointer to one character past the head of a path name.
  3623.  * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
  3624.  * If there is no head, path is returned.
  3625.  */
  3626.     char_u *
  3627. get_past_head(path)
  3628.     char_u  *path;
  3629. {
  3630.     char_u  *retval;
  3631.  
  3632. #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
  3633.     /* may skip "c:" */
  3634.     if (isalpha(path[0]) && path[1] == ':')
  3635.     retval = path + 2;
  3636.     else
  3637.     retval = path;
  3638. #else
  3639. # if defined(AMIGA)
  3640.     /* may skip "label:" */
  3641.     retval = vim_strchr(path, ':');
  3642.     if (retval == NULL)
  3643.     retval = path;
  3644. # else    /* Unix */
  3645.     retval = path;
  3646. # endif
  3647. #endif
  3648.  
  3649.     while (vim_ispathsep(*retval))
  3650.     ++retval;
  3651.  
  3652.     return retval;
  3653. }
  3654.  
  3655. /*
  3656.  * return TRUE if 'c' is a path separator.
  3657.  */
  3658.     int
  3659. vim_ispathsep(c)
  3660.     int c;
  3661. {
  3662. #ifdef RISCOS
  3663.     return (c == '.' || c == ':');
  3664. #else
  3665. # ifdef UNIX
  3666.     return (c == '/');        /* UNIX has ':' inside file names */
  3667. # else
  3668. #  ifdef BACKSLASH_IN_FILENAME
  3669.     return (c == ':' || c == '/' || c == '\\');
  3670. #  else
  3671. #   ifdef VMS
  3672.     /* server"user passwd"::device:[full.path.name]fname.extension;version" */
  3673.     return (c == ':' || c == '[' || c == ']' || c == '/'
  3674.         || c == '<' || c == '>' || c == '"' );
  3675. #   else
  3676. #    ifdef COLON_AS_PATHSEP
  3677.     return (c == ':');
  3678. #    else        /* Amiga */
  3679.     return (c == ':' || c == '/');
  3680. #    endif
  3681. #   endif /* VMS */
  3682. #  endif
  3683. # endif
  3684. #endif /* RISC OS */
  3685. }
  3686.  
  3687. #if defined(FEAT_SEARCHPATH) || defined(PROTO)
  3688. /*
  3689.  * return TRUE if 'c' is a path list separator.
  3690.  */
  3691.     int
  3692. vim_ispathlistsep(c)
  3693.     int c;
  3694. {
  3695. #ifdef UNIX
  3696.     return (c == ':');
  3697. #else
  3698.     return (c == ';');    /* might not be rigth for every system... */
  3699. #endif
  3700. }
  3701. #endif
  3702.  
  3703. #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
  3704.     || defined(PROTO)
  3705. /*
  3706.  * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
  3707.  */
  3708.     int
  3709. vim_fnamecmp(x, y)
  3710.     char_u    *x, *y;
  3711. {
  3712.     return vim_fnamencmp(x, y, MAXPATHL);
  3713. }
  3714.  
  3715.     int
  3716. vim_fnamencmp(x, y, len)
  3717.     char_u    *x, *y;
  3718.     size_t    len;
  3719. {
  3720.     while (len > 0 && *x && *y)
  3721.     {
  3722.     if (TO_LOWER(*x) != TO_LOWER(*y)
  3723.         && !(*x == '/' && *y == '\\')
  3724.         && !(*x == '\\' && *y == '/'))
  3725.         break;
  3726.     ++x;
  3727.     ++y;
  3728.     --len;
  3729.     }
  3730.     if (len <= 0)
  3731.     return 0;
  3732.     return (*x - *y);
  3733. }
  3734. #endif
  3735.  
  3736. /*
  3737.  * Concatenate file names fname1 and fname2 into allocated memory.
  3738.  * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
  3739.  */
  3740.     char_u  *
  3741. concat_fnames(fname1, fname2, sep)
  3742.     char_u  *fname1;
  3743.     char_u  *fname2;
  3744.     int        sep;
  3745. {
  3746.     char_u  *dest;
  3747.  
  3748.     dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
  3749.     if (dest != NULL)
  3750.     {
  3751.     STRCPY(dest, fname1);
  3752.     if (sep)
  3753.         add_pathsep(dest);
  3754.     STRCAT(dest, fname2);
  3755.     }
  3756.     return dest;
  3757. }
  3758.  
  3759. /*
  3760.  * Add a path separator to a file name, unless it already ends in a path
  3761.  * separator.
  3762.  */
  3763.     void
  3764. add_pathsep(p)
  3765.     char_u    *p;
  3766. {
  3767.     if (*p != NUL && !vim_ispathsep(*(p + STRLEN(p) - 1)))
  3768.     STRCAT(p, PATHSEPSTR);
  3769. }
  3770.  
  3771. /*
  3772.  * FullName_save - Make an allocated copy of a full file name.
  3773.  * Returns NULL when out of memory.
  3774.  */
  3775.     char_u  *
  3776. FullName_save(fname, force)
  3777.     char_u    *fname;
  3778.     int        force;        /* force expansion, even when it already looks
  3779.                    like a full path name */
  3780. {
  3781.     char_u    *buf;
  3782.     char_u    *new_fname = NULL;
  3783.  
  3784.     if (fname == NULL)
  3785.     return NULL;
  3786.  
  3787.     buf = alloc((unsigned)MAXPATHL);
  3788.     if (buf != NULL)
  3789.     {
  3790.     if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
  3791.         new_fname = vim_strsave(buf);
  3792.     else
  3793.         new_fname = vim_strsave(fname);
  3794.     vim_free(buf);
  3795.     }
  3796.     return new_fname;
  3797. }
  3798.  
  3799. #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
  3800.  
  3801. static char_u    *skip_string __ARGS((char_u *p));
  3802.  
  3803. /*
  3804.  * Find the start of a comment, not knowing if we are in a comment right now.
  3805.  * Search starts at w_cursor.lnum and goes backwards.
  3806.  */
  3807.     pos_T *
  3808. find_start_comment(ind_maxcomment)        /* XXX */
  3809.     int        ind_maxcomment;
  3810. {
  3811.     pos_T    *pos;
  3812.     char_u    *line;
  3813.     char_u    *p;
  3814.  
  3815.     if ((pos = findmatchlimit(NULL, '*', FM_BACKWARD, ind_maxcomment)) == NULL)
  3816.     return NULL;
  3817.  
  3818.     /*
  3819.      * Check if the comment start we found is inside a string.
  3820.      */
  3821.     line = ml_get(pos->lnum);
  3822.     for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
  3823.     p = skip_string(p);
  3824.     if ((unsigned)(p - line) > pos->col)
  3825.     return NULL;
  3826.     return pos;
  3827. }
  3828.  
  3829. /*
  3830.  * Skip to the end of a "string" and a 'c' character.
  3831.  * If there is no string or character, return argument unmodified.
  3832.  */
  3833.     static char_u *
  3834. skip_string(p)
  3835.     char_u  *p;
  3836. {
  3837.     int        i;
  3838.  
  3839.     /*
  3840.      * We loop, because strings may be concatenated: "date""time".
  3841.      */
  3842.     for ( ; ; ++p)
  3843.     {
  3844.     if (p[0] == '\'')            /* 'c' or '\n' or '\000' */
  3845.     {
  3846.         if (!p[1])                /* ' at end of line */
  3847.         break;
  3848.         i = 2;
  3849.         if (p[1] == '\\')            /* '\n' or '\000' */
  3850.         {
  3851.         ++i;
  3852.         while (isdigit(p[i - 1]))   /* '\000' */
  3853.             ++i;
  3854.         }
  3855.         if (p[i] == '\'')            /* check for trailing ' */
  3856.         {
  3857.         p += i;
  3858.         continue;
  3859.         }
  3860.     }
  3861.     else if (p[0] == '"')            /* start of string */
  3862.     {
  3863.         for (++p; p[0]; ++p)
  3864.         {
  3865.         if (p[0] == '\\' && p[1] != NUL)
  3866.             ++p;
  3867.         else if (p[0] == '"')        /* end of string */
  3868.             break;
  3869.         }
  3870.         if (p[0] == '"')
  3871.         continue;
  3872.     }
  3873.     break;                    /* no string found */
  3874.     }
  3875.     if (!*p)
  3876.     --p;                    /* backup from NUL */
  3877.     return p;
  3878. }
  3879. #endif /* FEAT_CINDENT || FEAT_SYN_HL */
  3880.  
  3881. #if defined(FEAT_CINDENT) || defined(PROTO)
  3882.  
  3883. /*
  3884.  * Do C or expression indenting on the current line.
  3885.  */
  3886.     void
  3887. do_c_expr_indent()
  3888. {
  3889. # ifdef FEAT_EVAL
  3890.     if (*curbuf->b_p_inde != NUL)
  3891.     fixthisline(get_expr_indent);
  3892.     else
  3893. # endif
  3894.     fixthisline(get_c_indent);
  3895. }
  3896.  
  3897. /*
  3898.  * Functions for C-indenting.
  3899.  * Most of this originally comes from Eric Fischer.
  3900.  */
  3901. /*
  3902.  * Below "XXX" means that this function may unlock the current line.
  3903.  */
  3904.  
  3905. static char_u    *cin_skipcomment __ARGS((char_u *));
  3906. static int    cin_nocode __ARGS((char_u *));
  3907. static int    cin_islabel_skip __ARGS((char_u **));
  3908. static int    cin_isdefault __ARGS((char_u *));
  3909. static char_u    *after_label __ARGS((char_u *l));
  3910. static int    get_indent_nolabel __ARGS((linenr_T lnum));
  3911. static int    skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
  3912. static int    cin_ispreproc __ARGS((char_u *));
  3913. static int    cin_iscomment __ARGS((char_u *));
  3914. static int    cin_isterminated __ARGS((char_u *, int));
  3915. static int    cin_isfuncdecl __ARGS((char_u *));
  3916. static int    cin_isif __ARGS((char_u *));
  3917. static int    cin_iselse __ARGS((char_u *));
  3918. static int    cin_isdo __ARGS((char_u *));
  3919. static int    cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
  3920. static int    cin_ends_in __ARGS((char_u *, char_u *));
  3921. static int    cin_skip2pos __ARGS((pos_T *trypos));
  3922. static pos_T    *find_start_brace __ARGS((int));
  3923. static pos_T    *find_match_paren __ARGS((int, int));
  3924. static int    find_last_paren __ARGS((char_u *l));
  3925. static int    find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
  3926.  
  3927. /*
  3928.  * Skip over white space and C comments within the line.
  3929.  */
  3930.     static char_u *
  3931. cin_skipcomment(s)
  3932.     char_u    *s;
  3933. {
  3934.     while (*s)
  3935.     {
  3936.     s = skipwhite(s);
  3937.     if (*s != '/')
  3938.         break;
  3939.     ++s;
  3940.     if (*s == '/')        /* slash-slash comment continues till eol */
  3941.     {
  3942.         s += STRLEN(s);
  3943.         break;
  3944.     }
  3945.     if (*s != '*')
  3946.         break;
  3947.     for (++s; *s; ++s)    /* skip slash-star comment */
  3948.         if (s[0] == '*' && s[1] == '/')
  3949.         {
  3950.         s += 2;
  3951.         break;
  3952.         }
  3953.     }
  3954.     return s;
  3955. }
  3956.  
  3957. /*
  3958.  * Return TRUE if there there is no code at *s.  White space and comments are
  3959.  * not considered code.
  3960.  */
  3961.     static int
  3962. cin_nocode(s)
  3963.     char_u    *s;
  3964. {
  3965.     return *cin_skipcomment(s) == NUL;
  3966. }
  3967.  
  3968. /*
  3969.  * Check if string matches "label:"; move to character after ':' if true.
  3970.  */
  3971.     static int
  3972. cin_islabel_skip(s)
  3973.     char_u    **s;
  3974. {
  3975.     if (!vim_isIDc(**s))        /* need at least one ID character */
  3976.     return FALSE;
  3977.  
  3978.     while (vim_isIDc(**s))
  3979.     (*s)++;
  3980.  
  3981.     *s = cin_skipcomment(*s);
  3982.  
  3983.     /* "::" is not a label, it's C++ */
  3984.     return (**s == ':' && *++*s != ':');
  3985. }
  3986.  
  3987. /*
  3988.  * Recognize a label: "label:".
  3989.  * Note: curwin->w_cursor must be where we are looking for the label.
  3990.  */
  3991.     int
  3992. cin_islabel(ind_maxcomment)        /* XXX */
  3993.     int        ind_maxcomment;
  3994. {
  3995.     char_u    *s;
  3996.  
  3997.     s = cin_skipcomment(ml_get_curline());
  3998.  
  3999.     /*
  4000.      * Exclude "default" from labels, since it should be indented
  4001.      * like a switch label.  Same for C++ scope declarations.
  4002.      */
  4003.     if (cin_isdefault(s))
  4004.     return FALSE;
  4005.     if (cin_isscopedecl(s))
  4006.     return FALSE;
  4007.  
  4008.     if (cin_islabel_skip(&s))
  4009.     {
  4010.     /*
  4011.      * Only accept a label if the previous line is terminated or is a case
  4012.      * label.
  4013.      */
  4014.     pos_T    cursor_save;
  4015.     pos_T    *trypos;
  4016.     char_u    *line;
  4017.  
  4018.     cursor_save = curwin->w_cursor;
  4019.     while (curwin->w_cursor.lnum > 1)
  4020.     {
  4021.         --curwin->w_cursor.lnum;
  4022.  
  4023.         /*
  4024.          * If we're in a comment now, skip to the start of the comment.
  4025.          */
  4026.         curwin->w_cursor.col = 0;
  4027.         if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
  4028.         curwin->w_cursor = *trypos;
  4029.  
  4030.         line = ml_get_curline();
  4031.         if (cin_ispreproc(line))    /* ignore #defines, #if, etc. */
  4032.         continue;
  4033.         if (*(line = cin_skipcomment(line)) == NUL)
  4034.         continue;
  4035.  
  4036.         curwin->w_cursor = cursor_save;
  4037.         if (cin_isterminated(line, TRUE)
  4038.             || cin_isscopedecl(line)
  4039.             || cin_iscase(line)
  4040.             || (cin_islabel_skip(&line) && cin_nocode(line)))
  4041.         return TRUE;
  4042.         return FALSE;
  4043.     }
  4044.     curwin->w_cursor = cursor_save;
  4045.     return TRUE;        /* label at start of file??? */
  4046.     }
  4047.     return FALSE;
  4048. }
  4049.  
  4050. /*
  4051.  * Recognize a switch label: "case .*:" or "default:".
  4052.  */
  4053.      int
  4054. cin_iscase(s)
  4055.     char_u *s;
  4056. {
  4057.     s = cin_skipcomment(s);
  4058.     if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
  4059.     {
  4060.     for (s += 4; *s; ++s)
  4061.     {
  4062.         s = cin_skipcomment(s);
  4063.         if (*s == ':')
  4064.         {
  4065.         if (s[1] == ':')    /* skip over "::" for C++ */
  4066.             ++s;
  4067.         else
  4068.             return TRUE;
  4069.         }
  4070.         if (*s == '\'' && s[1] && s[2] == '\'')
  4071.         s += 2;            /* skip over '.' */
  4072.         else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
  4073.         return FALSE;        /* stop at comment */
  4074.         else if (*s == '"')
  4075.         return FALSE;        /* stop at string */
  4076.     }
  4077.     return FALSE;
  4078.     }
  4079.  
  4080.     if (cin_isdefault(s))
  4081.     return TRUE;
  4082.     return FALSE;
  4083. }
  4084.  
  4085. /*
  4086.  * Recognize a "default" switch label.
  4087.  */
  4088.     static int
  4089. cin_isdefault(s)
  4090.     char_u  *s;
  4091. {
  4092.     return (STRNCMP(s, "default", 7) == 0
  4093.         && *(s = cin_skipcomment(s + 7)) == ':'
  4094.         && s[1] != ':');
  4095. }
  4096.  
  4097. /*
  4098.  * Recognize a "public/private/proctected" scope declaration label.
  4099.  */
  4100.     int
  4101. cin_isscopedecl(s)
  4102.     char_u    *s;
  4103. {
  4104.     int        i;
  4105.  
  4106.     s = cin_skipcomment(s);
  4107.     if (STRNCMP(s, "public", 6) == 0)
  4108.     i = 6;
  4109.     else if (STRNCMP(s, "protected", 9) == 0)
  4110.     i = 9;
  4111.     else if (STRNCMP(s, "private", 7) == 0)
  4112.     i = 7;
  4113.     else
  4114.     return FALSE;
  4115.     return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
  4116. }
  4117.  
  4118. /*
  4119.  * Return a pointer to the first non-empty non-comment character after a ':'.
  4120.  * Return NULL if not found.
  4121.  *      case 234:    a = b;
  4122.  *               ^
  4123.  */
  4124.     static char_u *
  4125. after_label(l)
  4126.     char_u  *l;
  4127. {
  4128.     for ( ; *l; ++l)
  4129.     {
  4130.     if (*l == ':')
  4131.     {
  4132.         if (l[1] == ':')        /* skip over "::" for C++ */
  4133.         ++l;
  4134.         else if (!cin_iscase(l + 1))
  4135.         break;
  4136.     }
  4137.     else if (*l == '\'' && l[1] && l[2] == '\'')
  4138.         l += 2;            /* skip over 'x' */
  4139.     }
  4140.     if (*l == NUL)
  4141.     return NULL;
  4142.     l = cin_skipcomment(l + 1);
  4143.     if (*l == NUL)
  4144.     return NULL;
  4145.     return l;
  4146. }
  4147.  
  4148. /*
  4149.  * Get indent of line "lnum", skipping a label.
  4150.  * Return 0 if there is nothing after the label.
  4151.  */
  4152.     static int
  4153. get_indent_nolabel(lnum)        /* XXX */
  4154.     linenr_T    lnum;
  4155. {
  4156.     char_u    *l;
  4157.     pos_T    fp;
  4158.     colnr_T    col;
  4159.     char_u    *p;
  4160.  
  4161.     l = ml_get(lnum);
  4162.     p = after_label(l);
  4163.     if (p == NULL)
  4164.     return 0;
  4165.  
  4166.     fp.col = (colnr_T)(p - l);
  4167.     fp.lnum = lnum;
  4168.     getvcol(curwin, &fp, &col, NULL, NULL);
  4169.     return (int)col;
  4170. }
  4171.  
  4172. /*
  4173.  * Find indent for line "lnum", ignoring any case or jump label.
  4174.  * Also return a pointer to the text (after the label).
  4175.  *   label:    if (asdf && asdfasdf)
  4176.  *        ^
  4177.  */
  4178.     static int
  4179. skip_label(lnum, pp, ind_maxcomment)
  4180.     linenr_T    lnum;
  4181.     char_u    **pp;
  4182.     int        ind_maxcomment;
  4183. {
  4184.     char_u    *l;
  4185.     int        amount;
  4186.     pos_T    cursor_save;
  4187.  
  4188.     cursor_save = curwin->w_cursor;
  4189.     curwin->w_cursor.lnum = lnum;
  4190.     l = ml_get_curline();
  4191.                     /* XXX */
  4192.     if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
  4193.     {
  4194.     amount = get_indent_nolabel(lnum);
  4195.     l = after_label(ml_get_curline());
  4196.     if (l == NULL)        /* just in case */
  4197.         l = ml_get_curline();
  4198.     }
  4199.     else
  4200.     {
  4201.     amount = get_indent();
  4202.     l = ml_get_curline();
  4203.     }
  4204.     *pp = l;
  4205.  
  4206.     curwin->w_cursor = cursor_save;
  4207.     return amount;
  4208. }
  4209.  
  4210. /*
  4211.  * Recognize a preprocessor statement: Any line that starts with '#'.
  4212.  */
  4213.     static int
  4214. cin_ispreproc(s)
  4215.     char_u *s;
  4216. {
  4217.     s = skipwhite(s);
  4218.     if (*s == '#')
  4219.     return TRUE;
  4220.     return FALSE;
  4221. }
  4222.  
  4223. /*
  4224.  * Recognize the start of a C or C++ comment.
  4225.  */
  4226.     static int
  4227. cin_iscomment(p)
  4228.     char_u  *p;
  4229. {
  4230.     return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
  4231. }
  4232.  
  4233. /*
  4234.  * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
  4235.  * Don't consider "} else" a terminated line.
  4236.  * Also consider a line terminated if it ends in ','.  This is not 100%
  4237.  * correct, but this mostly means we are in initializations and then it's OK.
  4238.  */
  4239.     static int
  4240. cin_isterminated(s, incl_open)
  4241.     char_u    *s;
  4242.     int        incl_open;    /* include '{' at the end as terminator */
  4243. {
  4244.     s = cin_skipcomment(s);
  4245.  
  4246.     if (*s == '{' || (*s == '}' && !cin_iselse(s)))
  4247.     return TRUE;
  4248.  
  4249.     while (*s)
  4250.     {
  4251.     /* skip over comments, "" strings and 'c'haracters */
  4252.     s = skip_string(cin_skipcomment(s));
  4253.     if ((*s == ';' || (incl_open && *s == '{') || *s == '}' || *s == ',')
  4254.                              && cin_nocode(s + 1))
  4255.         return TRUE;
  4256.     if (*s)
  4257.         s++;
  4258.     }
  4259.     return FALSE;
  4260. }
  4261.  
  4262. /*
  4263.  * Recognize the basic picture of a function declaration -- it needs to
  4264.  * have an open paren somewhere and a close paren at the end of the line and
  4265.  * no semicolons anywhere.
  4266.  */
  4267.     static int
  4268. cin_isfuncdecl(s)
  4269.     char_u *s;
  4270. {
  4271.     while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
  4272.     {
  4273.     if (cin_iscomment(s))    /* ignore comments */
  4274.         s = cin_skipcomment(s);
  4275.     else
  4276.         ++s;
  4277.     }
  4278.     if (*s != '(')
  4279.     return FALSE;        /* ';', ' or "  before any () or no '(' */
  4280.  
  4281.     while (*s && *s != ';' && *s != '\'' && *s != '"')
  4282.     {
  4283.     if (*s == ')' && cin_nocode(s + 1))
  4284.         return TRUE;
  4285.     if (cin_iscomment(s))    /* ignore comments */
  4286.         s = cin_skipcomment(s);
  4287.     else
  4288.         ++s;
  4289.     }
  4290.     return FALSE;
  4291. }
  4292.  
  4293.     static int
  4294. cin_isif(p)
  4295.     char_u  *p;
  4296. {
  4297.     return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
  4298. }
  4299.  
  4300.     static int
  4301. cin_iselse(p)
  4302.     char_u  *p;
  4303. {
  4304.     if (*p == '}')        /* accept "} else" */
  4305.     p = cin_skipcomment(p + 1);
  4306.     return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
  4307. }
  4308.  
  4309.     static int
  4310. cin_isdo(p)
  4311.     char_u  *p;
  4312. {
  4313.     return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
  4314. }
  4315.  
  4316. /*
  4317.  * Check if this is a "while" that should have a matching "do".
  4318.  * We only accept a "while (condition) ;", with only white space between the
  4319.  * ')' and ';'. The condition may be spread over several lines.
  4320.  */
  4321.     static int
  4322. cin_iswhileofdo(p, lnum, ind_maxparen)        /* XXX */
  4323.     char_u    *p;
  4324.     linenr_T    lnum;
  4325.     int        ind_maxparen;
  4326. {
  4327.     pos_T    cursor_save;
  4328.     pos_T    *trypos;
  4329.     int        retval = FALSE;
  4330.  
  4331.     p = cin_skipcomment(p);
  4332.     if (*p == '}')        /* accept "} while (cond);" */
  4333.     p = cin_skipcomment(p + 1);
  4334.     if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
  4335.     {
  4336.     cursor_save = curwin->w_cursor;
  4337.     curwin->w_cursor.lnum = lnum;
  4338.     curwin->w_cursor.col = 0;
  4339.     p = ml_get_curline();
  4340.     while (*p && *p != 'w')    /* skip any '}', until the 'w' of the "while" */
  4341.     {
  4342.         ++p;
  4343.         ++curwin->w_cursor.col;
  4344.     }
  4345.     if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
  4346.         && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
  4347.         retval = TRUE;
  4348.     curwin->w_cursor = cursor_save;
  4349.     }
  4350.     return retval;
  4351. }
  4352.  
  4353. /*
  4354.  * Return TRUE if string "s" ends with the string "find", possibly followed by
  4355.  * white space and comments.  Skip strings and comments.
  4356.  */
  4357.     static int
  4358. cin_ends_in(s, find)
  4359.     char_u    *s;
  4360.     char_u    *find;
  4361. {
  4362.     char_u    *p = s;
  4363.     char_u    *r;
  4364.     int        len = (int)STRLEN(find);
  4365.  
  4366.     while (*p != NUL)
  4367.     {
  4368.     p = cin_skipcomment(p);
  4369.     if (STRNCMP(p, find, len) == 0)
  4370.     {
  4371.         r = skipwhite(p + len);
  4372.         if (*r == NUL || cin_iscomment(r))
  4373.         return TRUE;
  4374.     }
  4375.     if (*p != NUL)
  4376.         ++p;
  4377.     }
  4378.     return FALSE;
  4379. }
  4380.  
  4381. /*
  4382.  * Skip strings, chars and comments until at or past "trypos".
  4383.  * Return the column found.
  4384.  */
  4385.     static int
  4386. cin_skip2pos(trypos)
  4387.     pos_T    *trypos;
  4388. {
  4389.     char_u    *line;
  4390.     char_u    *p;
  4391.  
  4392.     p = line = ml_get(trypos->lnum);
  4393.     while (*p && (colnr_T)(p - line) < trypos->col)
  4394.     {
  4395.     if (cin_iscomment(p))
  4396.         p = cin_skipcomment(p);
  4397.     else
  4398.     {
  4399.         p = skip_string(p);
  4400.         ++p;
  4401.     }
  4402.     }
  4403.     return (int)(p - line);
  4404. }
  4405.  
  4406. /*
  4407.  * Find the '{' at the start of the block we are in.
  4408.  * Return NULL if no match found.
  4409.  * Ignore a '{' that is in a comment, makes indenting the next three lines
  4410.  * work. */
  4411. /* foo()    */
  4412. /* {        */
  4413. /* }        */
  4414.  
  4415.     static pos_T *
  4416. find_start_brace(ind_maxcomment)        /* XXX */
  4417.     int        ind_maxcomment;
  4418. {
  4419.     pos_T    cursor_save;
  4420.     pos_T    *trypos;
  4421.     pos_T    *pos;
  4422.     static pos_T    pos_copy;
  4423.  
  4424.     cursor_save = curwin->w_cursor;
  4425.     while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
  4426.     {
  4427.     pos_copy = *trypos;    /* copy pos_T, next findmatch will change it */
  4428.     trypos = &pos_copy;
  4429.     curwin->w_cursor = *trypos;
  4430.     pos = NULL;
  4431.     /* ignore the { if it's in a // comment */
  4432.     if ((colnr_T)cin_skip2pos(trypos) == trypos->col
  4433.         && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
  4434.         break;
  4435.     if (pos != NULL)
  4436.         curwin->w_cursor.lnum = pos->lnum;
  4437.     }
  4438.     curwin->w_cursor = cursor_save;
  4439.     return trypos;
  4440. }
  4441.  
  4442. /*
  4443.  * Find the matching '(', failing if it is in a comment.
  4444.  * Return NULL of no match found.
  4445.  */
  4446.     static pos_T *
  4447. find_match_paren(ind_maxparen, ind_maxcomment)        /* XXX */
  4448.     int        ind_maxparen;
  4449.     int        ind_maxcomment;
  4450. {
  4451.     pos_T    cursor_save;
  4452.     pos_T    *trypos;
  4453.     static pos_T    pos_copy;
  4454.  
  4455.     cursor_save = curwin->w_cursor;
  4456.     if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
  4457.     {
  4458.     /* check if the ( is in a // comment */
  4459.     if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
  4460.         trypos = NULL;
  4461.     else
  4462.     {
  4463.         pos_copy = *trypos;        /* copy trypos, findmatch will change it */
  4464.         trypos = &pos_copy;
  4465.         curwin->w_cursor = *trypos;
  4466.         if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
  4467.         trypos = NULL;
  4468.     }
  4469.     }
  4470.     curwin->w_cursor = cursor_save;
  4471.     return trypos;
  4472. }
  4473.  
  4474. /*
  4475.  * Set w_cursor.col to the column number of the last ')' in line "l".
  4476.  */
  4477.     static int
  4478. find_last_paren(l)
  4479.     char_u *l;
  4480. {
  4481.     int        i;
  4482.     int        retval = FALSE;
  4483.  
  4484.     curwin->w_cursor.col = 0;            /* default is start of line */
  4485.  
  4486.     for (i = 0; l[i]; i++)
  4487.     {
  4488.     i = (int)(skip_string(l + i) - l);    /* ignore parens in quotes */
  4489.     if (l[i] == ')')
  4490.     {
  4491.         curwin->w_cursor.col = i;
  4492.         retval = TRUE;
  4493.     }
  4494.     }
  4495.     return retval;
  4496. }
  4497.  
  4498.     int
  4499. get_c_indent()
  4500. {
  4501.     /*
  4502.      * spaces from a block's opening brace the prevailing indent for that
  4503.      * block should be
  4504.      */
  4505.     int ind_level = curbuf->b_p_sw;
  4506.  
  4507.     /*
  4508.      * spaces from the edge of the line an open brace that's at the end of a
  4509.      * line is imagined to be.
  4510.      */
  4511.     int ind_open_imag = 0;
  4512.  
  4513.     /*
  4514.      * spaces from the prevailing indent for a line that is not precededof by
  4515.      * an opening brace.
  4516.      */
  4517.     int ind_no_brace = 0;
  4518.  
  4519.     /*
  4520.      * column where the first { of a function should be located }
  4521.      */
  4522.     int ind_first_open = 0;
  4523.  
  4524.     /*
  4525.      * spaces from the prevailing indent a leftmost open brace should be
  4526.      * located
  4527.      */
  4528.     int ind_open_extra = 0;
  4529.  
  4530.     /*
  4531.      * spaces from the matching open brace (real location for one at the left
  4532.      * edge; imaginary location from one that ends a line) the matching close
  4533.      * brace should be located
  4534.      */
  4535.     int ind_close_extra = 0;
  4536.  
  4537.     /*
  4538.      * spaces from the edge of the line an open brace sitting in the leftmost
  4539.      * column is imagined to be
  4540.      */
  4541.     int ind_open_left_imag = 0;
  4542.  
  4543.     /*
  4544.      * spaces from the switch() indent a "case xx" label should be located
  4545.      */
  4546.     int ind_case = curbuf->b_p_sw;
  4547.  
  4548.     /*
  4549.      * spaces from the "case xx:" code after a switch() should be located
  4550.      */
  4551.     int ind_case_code = curbuf->b_p_sw;
  4552.  
  4553.     /*
  4554.      * spaces from the class declaration indent a scope declaration label
  4555.      * should be located
  4556.      */
  4557.     int ind_scopedecl = curbuf->b_p_sw;
  4558.  
  4559.     /*
  4560.      * spaces from the scope declaration label code should be located
  4561.      */
  4562.     int ind_scopedecl_code = curbuf->b_p_sw;
  4563.  
  4564.     /*
  4565.      * amount K&R-style parameters should be indented
  4566.      */
  4567.     int ind_param = curbuf->b_p_sw;
  4568.  
  4569.     /*
  4570.      * amount a function type spec should be indented
  4571.      */
  4572.     int ind_func_type = curbuf->b_p_sw;
  4573.  
  4574.     /*
  4575.      * additional spaces beyond the prevailing indent a continuation line
  4576.      * should be located
  4577.      */
  4578.     int ind_continuation = curbuf->b_p_sw;
  4579.  
  4580.     /*
  4581.      * spaces from the indent of the line with an unclosed parentheses
  4582.      */
  4583.     int ind_unclosed = curbuf->b_p_sw * 2;
  4584.  
  4585.     /*
  4586.      * spaces from the indent of the line with an unclosed parentheses, which
  4587.      * itself is also unclosed
  4588.      */
  4589.     int ind_unclosed2 = curbuf->b_p_sw;
  4590.  
  4591.     /*
  4592.      * suppress ignoring spaces from the indent of a line starting with an
  4593.      * unclosed parentheses.
  4594.      */
  4595.     int ind_unclosed_noignore = 0;
  4596.  
  4597.     /*
  4598.      * suppress ignoring white space when lining up with the character after
  4599.      * an unclosed parentheses.
  4600.      */
  4601.     int ind_unclosed_whiteok = 0;
  4602.  
  4603.     /*
  4604.      * indent a closing parentheses under the line start of the matching
  4605.      * opening parentheses.
  4606.      */
  4607.     int ind_matching_paren = 0;
  4608.  
  4609.     /*
  4610.      * spaces from the comment opener when there is nothing after it.
  4611.      */
  4612.     int ind_in_comment = 3;
  4613.  
  4614.     /*
  4615.      * boolean: if non-zero, use ind_in_comment even if there is something
  4616.      * after the comment opener.
  4617.      */
  4618.     int ind_in_comment2 = 0;
  4619.  
  4620.     /*
  4621.      * max lines to search for an open paren
  4622.      */
  4623.     int ind_maxparen = 20;
  4624.  
  4625.     /*
  4626.      * max lines to search for an open comment
  4627.      */
  4628.     int ind_maxcomment = 70;
  4629.  
  4630.     /*
  4631.      * handle braces for java code
  4632.      */
  4633.     int    ind_java = 0;
  4634.  
  4635.     /*
  4636.      * handle blocked cases correctly
  4637.      */
  4638.     int ind_keep_case_label = 0;
  4639.  
  4640.     pos_T    cur_curpos;
  4641.     int        amount;
  4642.     int        scope_amount;
  4643.     int        cur_amount;
  4644.     colnr_T    col;
  4645.     char_u    *theline;
  4646.     char_u    *linecopy;
  4647.     pos_T    *trypos;
  4648.     pos_T    *tryposBrace = NULL;
  4649.     pos_T    our_paren_pos;
  4650.     char_u    *start;
  4651.     int        start_brace;
  4652. #define BRACE_IN_COL0        1        /* '{' is in comumn 0 */
  4653. #define BRACE_AT_START        2        /* '{' is at start of line */
  4654. #define BRACE_AT_END        3        /* '{' is at end of line */
  4655.     linenr_T    ourscope;
  4656.     char_u    *l;
  4657.     char_u    *look;
  4658.     int        lookfor;
  4659. #define LOOKFOR_IF        1
  4660. #define LOOKFOR_DO        2
  4661. #define LOOKFOR_CASE        3
  4662. #define LOOKFOR_ANY        4
  4663. #define LOOKFOR_TERM        5
  4664. #define LOOKFOR_UNTERM        6
  4665. #define LOOKFOR_SCOPEDECL    7
  4666.     int        whilelevel;
  4667.     linenr_T    lnum;
  4668.     char_u    *options;
  4669.     int        fraction = 0;        /* init for GCC */
  4670.     int        divider;
  4671.     int        n;
  4672.     int        iscase;
  4673.  
  4674.     for (options = curbuf->b_p_cino; *options; )
  4675.     {
  4676.     l = options++;
  4677.     if (*options == '-')
  4678.         ++options;
  4679.     n = getdigits(&options);
  4680.     divider = 0;
  4681.     if (*options == '.')        /* ".5s" means a fraction */
  4682.     {
  4683.         fraction = atol((char *)++options);
  4684.         while (isdigit(*options))
  4685.         {
  4686.         ++options;
  4687.         if (divider)
  4688.             divider *= 10;
  4689.         else
  4690.             divider = 10;
  4691.         }
  4692.     }
  4693.     if (*options == 's')        /* "2s" means two times 'shiftwidth' */
  4694.     {
  4695.         if (n == 0 && fraction == 0)
  4696.         n = curbuf->b_p_sw;    /* just "s" is one 'shiftwidth' */
  4697.         else
  4698.         {
  4699.         n *= curbuf->b_p_sw;
  4700.         if (divider)
  4701.             n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
  4702.         }
  4703.         ++options;
  4704.     }
  4705.     if (l[1] == '-')
  4706.         n = -n;
  4707.     /* When adding an entry here, also update the default 'cinoptions' in
  4708.      * change.txt, and add explanation for it! */
  4709.     switch (*l)
  4710.     {
  4711.         case '>': ind_level = n; break;
  4712.         case 'e': ind_open_imag = n; break;
  4713.         case 'n': ind_no_brace = n; break;
  4714.         case 'f': ind_first_open = n; break;
  4715.         case '{': ind_open_extra = n; break;
  4716.         case '}': ind_close_extra = n; break;
  4717.         case '^': ind_open_left_imag = n; break;
  4718.         case ':': ind_case = n; break;
  4719.         case '=': ind_case_code = n; break;
  4720.         case 'p': ind_param = n; break;
  4721.         case 't': ind_func_type = n; break;
  4722.         case 'c': ind_in_comment = n; break;
  4723.         case 'C': ind_in_comment2 = n; break;
  4724.         case '+': ind_continuation = n; break;
  4725.         case '(': ind_unclosed = n; break;
  4726.         case 'u': ind_unclosed2 = n; break;
  4727.         case 'U': ind_unclosed_noignore = n; break;
  4728.         case 'w': ind_unclosed_whiteok = n; break;
  4729.         case 'm': ind_matching_paren = n; break;
  4730.         case ')': ind_maxparen = n; break;
  4731.         case '*': ind_maxcomment = n; break;
  4732.         case 'g': ind_scopedecl = n; break;
  4733.         case 'h': ind_scopedecl_code = n; break;
  4734.         case 'j': ind_java = n; break;
  4735.         case 'l': ind_keep_case_label = n; break;
  4736.     }
  4737.     }
  4738.  
  4739.     /* remember where the cursor was when we started */
  4740.  
  4741.     cur_curpos = curwin->w_cursor;
  4742.  
  4743.     /* get the current contents of the line.
  4744.      * This is required, because only the most recent line obtained with
  4745.      * ml_get is valid! */
  4746.  
  4747.     linecopy = vim_strsave(ml_get(cur_curpos.lnum));
  4748.     if (linecopy == NULL)
  4749.     return 0;
  4750.  
  4751.     /*
  4752.      * In insert mode and the cursor is on a ')' truncate the line at the
  4753.      * cursor position.  We don't want to line up with the matching '(' when
  4754.      * inserting new stuff.
  4755.      */
  4756.     if ((State & INSERT) && linecopy[curwin->w_cursor.col] == ')')
  4757.     linecopy[curwin->w_cursor.col] = NUL;
  4758.  
  4759.     theline = skipwhite(linecopy);
  4760.  
  4761.     /* move the cursor to the start of the line */
  4762.  
  4763.     curwin->w_cursor.col = 0;
  4764.  
  4765.     /*
  4766.      * #defines and so on always go at the left when included in 'cinkeys'.
  4767.      */
  4768.     if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
  4769.     {
  4770.     amount = 0;
  4771.     }
  4772.  
  4773.     /*
  4774.      * Is it a non-case label?    Then that goes at the left margin too.
  4775.      */
  4776.     else if (cin_islabel(ind_maxcomment))        /* XXX */
  4777.     {
  4778.     amount = 0;
  4779.     }
  4780.  
  4781.     /*
  4782.      * If we're inside a comment and not looking at the start of the
  4783.      * comment, try using the 'comments' option.
  4784.      */
  4785.     else if (!cin_iscomment(theline)
  4786.         && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
  4787.     {
  4788.     int    lead_start_len = 2;
  4789.     char_u    lead_middle[COM_MAX_LEN];    /* middle-comment string */
  4790.     char_u    lead_end[COM_MAX_LEN];        /* end-comment string */
  4791.     char_u    *p;
  4792.     int    start_align = 0;
  4793.     int    start_off = 0;
  4794.     int    done = FALSE;
  4795.  
  4796.     /* find how indented the line beginning the comment is */
  4797.     getvcol(curwin, trypos, &col, NULL, NULL);
  4798.     amount = col;
  4799.  
  4800.     p = curbuf->b_p_com;
  4801.     while (*p != NUL)
  4802.     {
  4803.         int    align = 0;
  4804.         int    off = 0;
  4805.         int what = 0;
  4806.  
  4807.         while (*p != NUL && *p != ':')
  4808.         {
  4809.         if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
  4810.             what = *p++;
  4811.         else if (*p == COM_LEFT || *p == COM_RIGHT)
  4812.             align = *p++;
  4813.         else if (isdigit(*p) || *p == '-')
  4814.             off = getdigits(&p);
  4815.         else
  4816.             ++p;
  4817.         }
  4818.  
  4819.         if (*p == ':')
  4820.         ++p;
  4821.         (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
  4822.         if (what == COM_START)
  4823.         {
  4824.         lead_start_len = (int)STRLEN(lead_end);
  4825.         start_off = off;
  4826.         start_align = align;
  4827.         }
  4828.         else if (what == COM_MIDDLE)
  4829.         {
  4830.         STRCPY(lead_middle, lead_end);
  4831.         }
  4832.         else if (what == COM_END)
  4833.         {
  4834.         /* If our line starts with the middle comment string, line it
  4835.          * up with the comment opener per the 'comments' option. */
  4836.         if (STRNCMP(theline, lead_middle, STRLEN(lead_middle)) == 0
  4837.             && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
  4838.         {
  4839.             if (start_off != 0)
  4840.             amount += start_off;
  4841.             else if (start_align == COM_RIGHT)
  4842.             amount += lead_start_len - (int)STRLEN(lead_middle);
  4843.             done = TRUE;
  4844.             break;
  4845.         }
  4846.  
  4847.         /* If our line starts with the end comment string, line it up
  4848.          * with the middle comment */
  4849.         if (STRNCMP(theline, lead_middle, STRLEN(lead_middle)) != 0
  4850.             && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
  4851.         {
  4852.             amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
  4853.                                      /* XXX */
  4854.             if (off != 0)
  4855.             amount += off;
  4856.             else if (align == COM_RIGHT)
  4857.             amount += lead_start_len - (int)STRLEN(lead_middle);
  4858.             done = TRUE;
  4859.             break;
  4860.         }
  4861.         }
  4862.     }
  4863.  
  4864.     /* If our line starts with an asterisk, line up with the
  4865.      * asterisk in the comment opener; otherwise, line up
  4866.      * with the first character of the comment text.
  4867.      */
  4868.     if (done)
  4869.         ;
  4870.     else if (theline[0] == '*')
  4871.         amount += 1;
  4872.     else
  4873.     {
  4874.         /*
  4875.          * If we are more than one line away from the comment opener, take
  4876.          * the indent of the previous non-empty line.  If 'cino' has "CO"
  4877.          * and we are just below the comment opener and there are any
  4878.          * white characters after it line up with the text after it;
  4879.          * otherwise, add the amount specified by "c" in 'cino'
  4880.          */
  4881.         amount = -1;
  4882.         for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
  4883.         {
  4884.         if (linewhite(lnum))            /* skip blank lines */
  4885.             continue;
  4886.         amount = get_indent_lnum(lnum);        /* XXX */
  4887.         break;
  4888.         }
  4889.         if (amount == -1)                /* use the comment opener */
  4890.         {
  4891.         if (!ind_in_comment2)
  4892.         {
  4893.             start = ml_get(trypos->lnum);
  4894.             look = start + trypos->col + 2; /* skip / and * */
  4895.             if (*look != NUL)            /* if something after it */
  4896.             trypos->col = (colnr_T)(skipwhite(look) - start);
  4897.         }
  4898.         getvcol(curwin, trypos, &col, NULL, NULL);
  4899.         amount = col;
  4900.         if (ind_in_comment2 || *look == NUL)
  4901.             amount += ind_in_comment;
  4902.         }
  4903.     }
  4904.     }
  4905.  
  4906.     /*
  4907.      * Are we inside parentheses or braces?
  4908.      */                            /* XXX */
  4909.     else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
  4910.         && ind_java == 0)
  4911.         || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
  4912.         || trypos != NULL)
  4913.     {
  4914.       if (trypos != NULL && tryposBrace != NULL)
  4915.       {
  4916.       /* Both an unmatched '(' and '{' is found.  Use the one which is
  4917.        * closer to the current cursor position, set the other to NULL. */
  4918.       if (trypos->lnum != tryposBrace->lnum
  4919.           ? trypos->lnum < tryposBrace->lnum
  4920.           : trypos->col < tryposBrace->col)
  4921.           trypos = NULL;
  4922.       else
  4923.           tryposBrace = NULL;
  4924.       }
  4925.  
  4926.       if (trypos != NULL)
  4927.       {
  4928.     /*
  4929.      * If the matching paren is more than one line away, use the indent of
  4930.      * a previous non-empty line that matches the same paren.
  4931.      */
  4932.     amount = -1;
  4933.     our_paren_pos = *trypos;
  4934.     if (theline[0] != ')')
  4935.     {
  4936.         for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
  4937.         {
  4938.         l = skipwhite(ml_get(lnum));
  4939.         if (cin_nocode(l))        /* skip comment lines */
  4940.             continue;
  4941.         if (cin_ispreproc(l))        /* ignore #defines, #if, etc. */
  4942.             continue;
  4943.         curwin->w_cursor.lnum = lnum;
  4944.  
  4945.         /* Skip a comment. XXX */
  4946.         if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
  4947.         {
  4948.             lnum = trypos->lnum + 1;
  4949.             continue;
  4950.         }
  4951.  
  4952.         /* XXX */
  4953.         if ((trypos = find_match_paren(ind_maxparen,
  4954.                            ind_maxcomment)) != NULL &&
  4955.                      trypos->lnum == our_paren_pos.lnum &&
  4956.                          trypos->col == our_paren_pos.col)
  4957.         {
  4958.             amount = get_indent_lnum(lnum);    /* XXX */
  4959.             break;
  4960.         }
  4961.         }
  4962.     }
  4963.  
  4964.     /*
  4965.      * Line up with line where the matching paren is. XXX
  4966.      * If the line starts with a '(' or the indent for unclosed
  4967.      * parentheses is zero, line up with the unclosed parentheses.
  4968.      */
  4969.     if (amount == -1)
  4970.     {
  4971.         amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
  4972.         cur_amount = MAXCOL;
  4973.         if (theline[0] == ')' || ind_unclosed == 0
  4974.                || (!ind_unclosed_noignore && *skipwhite(look) == '('))
  4975.         {
  4976.         /*
  4977.          * If we're looking at a close paren, line up right there;
  4978.          * otherwise, line up with the next (non-white) character.
  4979.          */
  4980.         if (theline[0] != ')')
  4981.         {
  4982.             if (ind_unclosed_whiteok)
  4983.             our_paren_pos.col++;
  4984.             else
  4985.             {
  4986.             col = our_paren_pos.col + 1;
  4987.             l = ml_get(our_paren_pos.lnum);
  4988.             while (vim_iswhite(l[col]))
  4989.                 col++;
  4990.             if (l[col] != NUL)    /* In case of trailing space */
  4991.                 our_paren_pos.col = col;
  4992.             else
  4993.                 our_paren_pos.col++;
  4994.             }
  4995.         }
  4996.  
  4997.         /*
  4998.          * Find how indented the paren is, or the character after it
  4999.          * if we did the above "if".
  5000.          */
  5001.         getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
  5002.         cur_amount = col;
  5003.         }
  5004.  
  5005.         if (theline[0] == ')' && ind_matching_paren)
  5006.         {
  5007.         /* Line up with the start of the matching paren line. */
  5008.         }
  5009.         else if (ind_unclosed == 0 || (!ind_unclosed_noignore
  5010.                           && *skipwhite(look) == '('))
  5011.         amount = cur_amount;
  5012.         else
  5013.         {
  5014.         /* add ind_unclosed2 for each '(' before our matching one */
  5015.         col = our_paren_pos.col;
  5016.         while (our_paren_pos.col > 0)
  5017.         {
  5018.             --our_paren_pos.col;
  5019.             switch (*ml_get_pos(&our_paren_pos))
  5020.             {
  5021.             case '(': amount += ind_unclosed2;
  5022.                   col = our_paren_pos.col;
  5023.                   break;
  5024.             case ')': amount -= ind_unclosed2;
  5025.                   col = MAXCOL;
  5026.                   break;
  5027.             }
  5028.         }
  5029.  
  5030.         /* Use ind_unclosed once, when the first '(' is not inside
  5031.          * braces */
  5032.         if (col == MAXCOL)
  5033.             amount += ind_unclosed;
  5034.         else
  5035.         {
  5036.             curwin->w_cursor.lnum = our_paren_pos.lnum;
  5037.             curwin->w_cursor.col = col;
  5038.             if ((trypos = find_match_paren(ind_maxparen,
  5039.                              ind_maxcomment)) != NULL)
  5040.             amount += ind_unclosed2;
  5041.             else
  5042.             amount += ind_unclosed;
  5043.         }
  5044.         /*
  5045.          * For a line starting with ')' use the minimum of the two
  5046.          * positions, to avoid giving it more indent than the previous
  5047.          * lines:
  5048.          *  func_long_name(            if (x
  5049.          *    arg                    && yy
  5050.          *    )      ^ not here           )    ^ not here
  5051.          */
  5052.         if (cur_amount < amount)
  5053.             amount = cur_amount;
  5054.         }
  5055.     }
  5056.       }
  5057.  
  5058.       /*
  5059.        * Are we at least inside braces, then?
  5060.        */
  5061.       else
  5062.       {
  5063.     trypos = tryposBrace;
  5064.  
  5065.     ourscope = trypos->lnum;
  5066.     start = ml_get(ourscope);
  5067.  
  5068.     /*
  5069.      * Now figure out how indented the line is in general.
  5070.      * If the brace was at the start of the line, we use that;
  5071.      * otherwise, check out the indentation of the line as
  5072.      * a whole and then add the "imaginary indent" to that.
  5073.      */
  5074.     look = skipwhite(start);
  5075.     if (*look == '{')
  5076.     {
  5077.         getvcol(curwin, trypos, &col, NULL, NULL);
  5078.         amount = col;
  5079.         if (*start == '{')
  5080.         start_brace = BRACE_IN_COL0;
  5081.         else
  5082.         start_brace = BRACE_AT_START;
  5083.     }
  5084.     else
  5085.     {
  5086.         /*
  5087.          * that opening brace might have been on a continuation
  5088.          * line.  if so, find the start of the line.
  5089.          */
  5090.         curwin->w_cursor.lnum = ourscope;
  5091.  
  5092.         /*
  5093.          * position the cursor over the rightmost paren, so that
  5094.          * matching it will take us back to the start of the line.
  5095.          */
  5096.         lnum = ourscope;
  5097.         if (find_last_paren(start) &&
  5098.             (trypos = find_match_paren(ind_maxparen,
  5099.                              ind_maxcomment)) != NULL)
  5100.         lnum = trypos->lnum;
  5101.  
  5102.         /*
  5103.          * It could have been something like
  5104.          *       case 1: if (asdf &&
  5105.          *            ldfd) {
  5106.          *            }
  5107.          */
  5108.         if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
  5109.         amount = get_indent();
  5110.         else
  5111.         amount = skip_label(lnum, &l, ind_maxcomment);
  5112.  
  5113.         start_brace = BRACE_AT_END;
  5114.     }
  5115.  
  5116.     /*
  5117.      * if we're looking at a closing brace, that's where
  5118.      * we want to be.  otherwise, add the amount of room
  5119.      * that an indent is supposed to be.
  5120.      */
  5121.     if (theline[0] == '}')
  5122.     {
  5123.         /*
  5124.          * they may want closing braces to line up with something
  5125.          * other than the open brace.  indulge them, if so.
  5126.          */
  5127.         amount += ind_close_extra;
  5128.     }
  5129.     else
  5130.     {
  5131.         /*
  5132.          * If we're looking at an "else", try to find an "if"
  5133.          * to match it with.
  5134.          * If we're looking at a "while", try to find a "do"
  5135.          * to match it with.
  5136.          */
  5137.         lookfor = 0;
  5138.         if (cin_iselse(theline))
  5139.         lookfor = LOOKFOR_IF;
  5140.         else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
  5141.                                     /* XXX */
  5142.         lookfor = LOOKFOR_DO;
  5143.         if (lookfor)
  5144.         {
  5145.         curwin->w_cursor.lnum = cur_curpos.lnum;
  5146.         if (find_match(lookfor, ourscope, ind_maxparen,
  5147.                             ind_maxcomment) == OK)
  5148.         {
  5149.             amount = get_indent();    /* XXX */
  5150.             goto theend;
  5151.         }
  5152.         }
  5153.  
  5154.         /*
  5155.          * We get here if we are not on an "while-of-do" or "else" (or
  5156.          * failed to find a matching "if").
  5157.          * Search backwards for something to line up with.
  5158.          * First set amount for when we don't find anything.
  5159.          */
  5160.  
  5161.         /*
  5162.          * if the '{' is  _really_ at the left margin, use the imaginary
  5163.          * location of a left-margin brace.  Otherwise, correct the
  5164.          * location for ind_open_extra.
  5165.          */
  5166.  
  5167.         if (start_brace == BRACE_IN_COL0)        /* '{' is in column 0 */
  5168.         {
  5169.         amount = ind_open_left_imag;
  5170.         }
  5171.         else
  5172.         {
  5173.         if (start_brace == BRACE_AT_END)    /* '{' is at end of line */
  5174.             amount += ind_open_imag;
  5175.         else
  5176.         {
  5177.             /* Compensate for adding ind_open_extra later. */
  5178.             amount -= ind_open_extra;
  5179.             if (amount < 0)
  5180.             amount = 0;
  5181.         }
  5182.         }
  5183.  
  5184.         if (cin_iscase(theline))    /* it's a switch() label */
  5185.         {
  5186.         lookfor = LOOKFOR_CASE;    /* find a previous switch() label */
  5187.         amount += ind_case;
  5188.         }
  5189.         else if (cin_isscopedecl(theline))    /* private:, ... */
  5190.         {
  5191.         lookfor = LOOKFOR_SCOPEDECL;    /* class decl is this block */
  5192.         amount += ind_scopedecl;
  5193.         }
  5194.         else
  5195.         {
  5196.         lookfor = LOOKFOR_ANY;
  5197.         amount += ind_level;    /* ind_level from start of block */
  5198.         }
  5199.         scope_amount = amount;
  5200.         whilelevel = 0;
  5201.  
  5202.         /*
  5203.          * Search backwards.  If we find something we recognize, line up
  5204.          * with that.
  5205.          *
  5206.          * if we're looking at an open brace, indent
  5207.          * the usual amount relative to the conditional
  5208.          * that opens the block.
  5209.          */
  5210.         curwin->w_cursor = cur_curpos;
  5211.         for (;;)
  5212.         {
  5213.         curwin->w_cursor.lnum--;
  5214.         curwin->w_cursor.col = 0;
  5215.  
  5216.         /*
  5217.          * If we went all the way back to the start of our scope, line
  5218.          * up with it.
  5219.          */
  5220.         if (curwin->w_cursor.lnum <= ourscope)
  5221.         {
  5222.             if (lookfor == LOOKFOR_UNTERM)
  5223.             amount += ind_continuation;
  5224.             else if (lookfor != LOOKFOR_TERM)
  5225.             {
  5226.             amount = scope_amount;
  5227.             if (theline[0] == '{')
  5228.                 amount += ind_open_extra;
  5229.             }
  5230.             break;
  5231.         }
  5232.  
  5233.         /*
  5234.          * If we're in a comment now, skip to the start of the comment.
  5235.          */                        /* XXX */
  5236.         if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
  5237.         {
  5238.             curwin->w_cursor.lnum = trypos->lnum + 1;
  5239.             continue;
  5240.         }
  5241.  
  5242.         l = ml_get_curline();
  5243.  
  5244.         /*
  5245.          * If this is a switch() label, may line up relative to that.
  5246.          * if this is a C++ scope declaration, do the same.
  5247.          */
  5248.         iscase = cin_iscase(l);
  5249.         if (iscase || cin_isscopedecl(l))
  5250.         {
  5251.             /* When looking for a "do" we are not interested in
  5252.              * labels. */
  5253.             if (whilelevel > 0)
  5254.             continue;
  5255.  
  5256.             /*
  5257.              *    case xx:
  5258.              *        c = 99 +        <- this indent plus continuation
  5259.              *->       here;
  5260.              */
  5261.             if (lookfor == LOOKFOR_UNTERM)
  5262.             {
  5263.             amount += ind_continuation;
  5264.             break;
  5265.             }
  5266.  
  5267.             /*
  5268.              *    case xx:    <- line up with this case
  5269.              *        x = 333;
  5270.              *    case yy:
  5271.              */
  5272.             if (       (iscase && lookfor == LOOKFOR_CASE)
  5273.                 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
  5274.             {
  5275.             /*
  5276.              * Check that this case label is not for another
  5277.              * switch()
  5278.              */                    /* XXX */
  5279.             if ((trypos = find_start_brace(ind_maxcomment)) ==
  5280.                          NULL || trypos->lnum == ourscope)
  5281.             {
  5282.                 amount = get_indent();    /* XXX */
  5283.                 break;
  5284.             }
  5285.             continue;
  5286.             }
  5287.  
  5288.             n = get_indent_nolabel(curwin->w_cursor.lnum);  /* XXX */
  5289.  
  5290.             /*
  5291.              *     case xx: if (cond)        <- line up with this if
  5292.              *              y = y + 1;
  5293.              * ->      s = 99;
  5294.              *
  5295.              *     case xx:
  5296.              *         if (cond)        <- line up with this line
  5297.              *         y = y + 1;
  5298.              * ->    s = 99;
  5299.              */
  5300.             if (lookfor == LOOKFOR_TERM)
  5301.             {
  5302.             if (n)
  5303.                 amount = n;
  5304.             break;
  5305.             }
  5306.  
  5307.             /*
  5308.              *     case xx: x = x + 1;        <- line up with this x
  5309.              * ->      y = y + 1;
  5310.              *
  5311.              *     case xx: if (cond)        <- line up with this if
  5312.              * ->           y = y + 1;
  5313.              */
  5314.             if (n)
  5315.             {
  5316.             amount = n;
  5317.             l = after_label(ml_get_curline());
  5318.             if (l != NULL && cin_is_cinword(l))
  5319.                 amount += ind_level + ind_no_brace;
  5320.             break;
  5321.             }
  5322.  
  5323.             /*
  5324.              * Try to get the indent of a statement before the switch
  5325.              * label.  If nothing is found, line up relative to the
  5326.              * switch label.
  5327.              *        break;        <- may line up with this line
  5328.              *     case xx:
  5329.              * ->   y = 1;
  5330.              */
  5331.             scope_amount = get_indent() + (iscase    /* XXX */
  5332.                     ? ind_case_code : ind_scopedecl_code);
  5333.             lookfor = LOOKFOR_ANY;
  5334.             continue;
  5335.         }
  5336.  
  5337.         /*
  5338.          * Looking for a switch() label or C++ scope declaration,
  5339.          * ignore other lines.
  5340.          */
  5341.         if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
  5342.             continue;
  5343.  
  5344.         /*
  5345.          * Ignore jump labels with nothing after them.
  5346.          */
  5347.         if (cin_islabel(ind_maxcomment))
  5348.         {
  5349.             l = after_label(ml_get_curline());
  5350.             if (l == NULL || cin_nocode(l))
  5351.             continue;
  5352.         }
  5353.  
  5354.         /*
  5355.          * Ignore #defines, #if, etc.
  5356.          * Ignore comment and empty lines.
  5357.          * (need to get the line again, cin_islabel() may have
  5358.          * unlocked it)
  5359.          */
  5360.         l = ml_get_curline();
  5361.         if (cin_ispreproc(l) || cin_nocode(l))
  5362.             continue;
  5363.  
  5364.         /*
  5365.          * What happens next depends on the line being terminated.
  5366.          */
  5367.         if (!cin_isterminated(l, FALSE))
  5368.         {
  5369.             /*
  5370.              * if we're in the middle of a paren thing,
  5371.              * go back to the line that starts it so
  5372.              * we can get the right prevailing indent
  5373.              *       if ( foo &&
  5374.              *            bar )
  5375.              */
  5376.             /*
  5377.              * position the cursor over the rightmost paren, so that
  5378.              * matching it will take us back to the start of the line.
  5379.              */
  5380.             (void)find_last_paren(l);
  5381.             if ((trypos = find_match_paren(ind_maxparen,
  5382.                              ind_maxcomment)) != NULL)
  5383.             {
  5384.             /*
  5385.              * Check if we are on a case label now.  This is
  5386.              * handled above.
  5387.              *     case xx:  if ( asdf &&
  5388.              *            asdf)
  5389.              */
  5390.             curwin->w_cursor.lnum = trypos->lnum;
  5391.             l = ml_get_curline();
  5392.             if (cin_iscase(l) || cin_isscopedecl(l))
  5393.             {
  5394.                 ++curwin->w_cursor.lnum;
  5395.                 continue;
  5396.             }
  5397.             }
  5398.  
  5399.             /*
  5400.              * Get indent and pointer to text for current line,
  5401.              * ignoring any jump label.        XXX
  5402.              */
  5403.             cur_amount = skip_label(curwin->w_cursor.lnum,
  5404.                               &l, ind_maxcomment);
  5405.  
  5406.             /*
  5407.              * If this is just above the line we are indenting, and it
  5408.              * starts with a '{', line it up with this line.
  5409.              *        while (not)
  5410.              * ->    {
  5411.              *        }
  5412.              */
  5413.             if (lookfor != LOOKFOR_TERM && theline[0] == '{')
  5414.             {
  5415.             amount = cur_amount;
  5416.             /*
  5417.              * Only add ind_open_extra when the current line
  5418.              * doesn't start with a '{', which must have a match
  5419.              * in the same line (scope is the same).  Probably:
  5420.              *    { 1, 2 },
  5421.              * ->    { 3, 4 }
  5422.              */
  5423.             if (*skipwhite(l) != '{')
  5424.                 amount += ind_open_extra;
  5425.             break;
  5426.             }
  5427.  
  5428.             /*
  5429.              * Check if we are after an "if", "while", etc.
  5430.              * Also allow "   } else".
  5431.              */
  5432.             if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
  5433.             {
  5434.             /*
  5435.              * Found an unterminated line after an if (), line up
  5436.              * with the last one.
  5437.              *   if (cond)
  5438.              *        100 +
  5439.              * ->        here;
  5440.              */
  5441.             if (lookfor == LOOKFOR_UNTERM)
  5442.             {
  5443.                 amount += ind_continuation;
  5444.                 break;
  5445.             }
  5446.  
  5447.             /*
  5448.              * If this is just above the line we are indenting, we
  5449.              * are finished.
  5450.              *        while (not)
  5451.              * ->        here;
  5452.              * Otherwise this indent can be used when the line
  5453.              * before this is terminated.
  5454.              *    yyy;
  5455.              *    if (stat)
  5456.              *        while (not)
  5457.              *        xxx;
  5458.              * ->    here;
  5459.              */
  5460.             amount = cur_amount;
  5461.             if (theline[0] == '{')
  5462.                 amount += ind_open_extra;
  5463.             if (lookfor != LOOKFOR_TERM)
  5464.             {
  5465.                 amount += ind_level + ind_no_brace;
  5466.                 break;
  5467.             }
  5468.  
  5469.             /*
  5470.              * Special trick: when expecting the while () after a
  5471.              * do, line up with the while()
  5472.              *     do
  5473.              *        x = 1;
  5474.              * ->  here
  5475.              */
  5476.             l = skipwhite(ml_get_curline());
  5477.             if (cin_isdo(l))
  5478.             {
  5479.                 if (whilelevel == 0)
  5480.                 break;
  5481.                 --whilelevel;
  5482.             }
  5483.  
  5484.             /*
  5485.              * When searching for a terminated line, don't use the
  5486.              * one between the "if" and the "else".
  5487.              * Need to use the scope of this "else".  XXX
  5488.              * If whilelevel != 0 continue looking for a "do {".
  5489.              */
  5490.             if (cin_iselse(l)
  5491.                 && whilelevel == 0
  5492.                 && ((trypos = find_start_brace(ind_maxcomment))
  5493.                                     == NULL
  5494.                     || find_match(LOOKFOR_IF, trypos->lnum,
  5495.                     ind_maxparen, ind_maxcomment) == FAIL))
  5496.                 break;
  5497.             }
  5498.  
  5499.             /*
  5500.              * If we're below an unterminated line that is not an
  5501.              * "if" or something, we may line up with this line or
  5502.              * add someting for a continuation line, depending on
  5503.              * the line before this one.
  5504.              */
  5505.             else
  5506.             {
  5507.             /*
  5508.              * Found two unterminated lines on a row, line up with
  5509.              * the last one.
  5510.              *   c = 99 +
  5511.              *        100 +
  5512.              * ->        here;
  5513.              */
  5514.             if (lookfor == LOOKFOR_UNTERM)
  5515.                 break;
  5516.  
  5517.             /*
  5518.              * Found first unterminated line on a row, may line up
  5519.              * with this line, remember its indent
  5520.              *        100 +
  5521.              * ->        here;
  5522.              */
  5523.             amount = cur_amount;
  5524.             if (lookfor != LOOKFOR_TERM)
  5525.                 lookfor = LOOKFOR_UNTERM;
  5526.             }
  5527.         }
  5528.  
  5529.         /*
  5530.          * Check if we are after a while (cond);
  5531.          * If so: Ignore until the matching "do".
  5532.          */
  5533.                             /* XXX */
  5534.         else if (cin_iswhileofdo(l,
  5535.                      curwin->w_cursor.lnum, ind_maxparen))
  5536.         {
  5537.             /*
  5538.              * Found an unterminated line after a while ();, line up
  5539.              * with the last one.
  5540.              *        while (cond);
  5541.              *        100 +        <- line up with this one
  5542.              * ->        here;
  5543.              */
  5544.             if (lookfor == LOOKFOR_UNTERM)
  5545.             {
  5546.             amount += ind_continuation;
  5547.             break;
  5548.             }
  5549.  
  5550.             if (whilelevel == 0)
  5551.             {
  5552.             lookfor = LOOKFOR_TERM;
  5553.             amount = get_indent();        /* XXX */
  5554.             if (theline[0] == '{')
  5555.                 amount += ind_open_extra;
  5556.             }
  5557.             ++whilelevel;
  5558.         }
  5559.  
  5560.         /*
  5561.          * We are after a "normal" statement.
  5562.          * If we had another statement we can stop now and use the
  5563.          * indent of that other statement.
  5564.          * Otherwise the indent of the current statement may be used,
  5565.          * search backwards for the next "normal" statement.
  5566.          */
  5567.         else
  5568.         {
  5569.             /*
  5570.              * Handle "do {" line.
  5571.              */
  5572.             if (whilelevel > 0)
  5573.             {
  5574.             l = cin_skipcomment(ml_get_curline());
  5575.             if (cin_isdo(l))
  5576.             {
  5577.                 amount = get_indent();    /* XXX */
  5578.                 --whilelevel;
  5579.                 continue;
  5580.             }
  5581.             }
  5582.  
  5583.             /*
  5584.              * Found a terminated line above an unterminated line. Add
  5585.              * the amount for a continuation line.
  5586.              *     x = 1;
  5587.              *     y = foo +
  5588.              * ->    here;
  5589.              */
  5590.             if (lookfor == LOOKFOR_UNTERM)
  5591.             {
  5592.             amount += ind_continuation;
  5593.             break;
  5594.             }
  5595.  
  5596.             /*
  5597.              * Found a terminated line above a terminated line or "if"
  5598.              * etc. line. Use the amount of the line below us.
  5599.              *     x = 1;                x = 1;
  5600.              *     if (asdf)            y = 2;
  5601.              *         while (asdf)      ->here;
  5602.              *        here;
  5603.              * ->foo;
  5604.              */
  5605.             if (lookfor == LOOKFOR_TERM)
  5606.             {
  5607.             if (whilelevel == 0)
  5608.                 break;
  5609.             }
  5610.  
  5611.             /*
  5612.              * First line above the one we're indenting is terminated.
  5613.              * To know what needs to be done look further backward for
  5614.              * a terminated line.
  5615.              */
  5616.             else
  5617.             {
  5618.             /*
  5619.              * position the cursor over the rightmost paren, so
  5620.              * that matching it will take us back to the start of
  5621.              * the line.  Helps for:
  5622.              *     func(asdr,
  5623.              *          asdfasdf);
  5624.              *     here;
  5625.              */
  5626. term_again:
  5627.             l = ml_get_curline();
  5628.             if (find_last_paren(l) &&
  5629.                 (trypos = find_match_paren(ind_maxparen,
  5630.                              ind_maxcomment)) != NULL)
  5631.             {
  5632.                 /*
  5633.                  * Check if we are on a case label now.  This is
  5634.                  * handled above.
  5635.                  *       case xx:  if ( asdf &&
  5636.                  *                asdf)
  5637.                  */
  5638.                 curwin->w_cursor.lnum = trypos->lnum;
  5639.                 l = ml_get_curline();
  5640.                 if (cin_iscase(l) || cin_isscopedecl(l))
  5641.                 {
  5642.                 ++curwin->w_cursor.lnum;
  5643.                 continue;
  5644.                 }
  5645.             }
  5646.  
  5647.             /* When aligning with the case statement, don't align
  5648.              * with a statement after it.
  5649.              *  case 1: {   <-- don't use this { position
  5650.              *    stat;
  5651.              *  }
  5652.              *  case 2:
  5653.              *    stat;
  5654.              */
  5655.             iscase = (ind_keep_case_label && cin_iscase(l));
  5656.  
  5657.             /*
  5658.              * Get indent and pointer to text for current line,
  5659.              * ignoring any jump label.
  5660.              */
  5661.             amount = skip_label(curwin->w_cursor.lnum,
  5662.                               &l, ind_maxcomment);
  5663.  
  5664.             if (theline[0] == '{')
  5665.                 amount += ind_open_extra;
  5666.             /* See remark above: "Only add ind_open_extra.." */
  5667.             if (*skipwhite(l) == '{')
  5668.                 amount -= ind_open_extra;
  5669.             lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
  5670.  
  5671.             /*
  5672.              * If we're at the end of a block, skip to the start of
  5673.              * that block.
  5674.              */
  5675.             curwin->w_cursor.col = 0;
  5676.             if (*cin_skipcomment(l) == '}'
  5677.                 && (trypos = find_start_brace(ind_maxcomment))
  5678.                                 != NULL) /* XXX */
  5679.             {
  5680.                 curwin->w_cursor.lnum = trypos->lnum;
  5681.                 /* if not "else {" check for terminated again */
  5682.                 /* but skip block for "} else {" */
  5683.                 l = cin_skipcomment(ml_get_curline());
  5684.                 if (*l == '}' || !cin_iselse(l))
  5685.                 goto term_again;
  5686.                 ++curwin->w_cursor.lnum;
  5687.             }
  5688.             }
  5689.         }
  5690.         }
  5691.     }
  5692.       }
  5693.     }
  5694.  
  5695.     /*
  5696.      * ok -- we're not inside any sort of structure at all!
  5697.      *
  5698.      * this means we're at the top level, and everything should
  5699.      * basically just match where the previous line is, except
  5700.      * for the lines immediately following a function declaration,
  5701.      * which are K&R-style parameters and need to be indented.
  5702.      */
  5703.     else
  5704.     {
  5705.     /*
  5706.      * if our line starts with an open brace, forget about any
  5707.      * prevailing indent and make sure it looks like the start
  5708.      * of a function
  5709.      */
  5710.  
  5711.     if (theline[0] == '{')
  5712.     {
  5713.         amount = ind_first_open;
  5714.     }
  5715.  
  5716.     /*
  5717.      * If the NEXT line is a function declaration, the current
  5718.      * line needs to be indented as a function type spec.
  5719.      * Don't do this if the current line looks like a comment
  5720.      * or if the current line is terminated, ie. ends in ';'.
  5721.      */
  5722.     else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
  5723.         && !cin_nocode(theline)
  5724.         && cin_isfuncdecl(ml_get(cur_curpos.lnum + 1))
  5725.         && !cin_isterminated(theline, FALSE))
  5726.     {
  5727.         amount = ind_func_type;
  5728.     }
  5729.     else
  5730.     {
  5731.         amount = 0;
  5732.         curwin->w_cursor = cur_curpos;
  5733.  
  5734.         /* search backwards until we find something we recognize */
  5735.  
  5736.         while (curwin->w_cursor.lnum > 1)
  5737.         {
  5738.         curwin->w_cursor.lnum--;
  5739.         curwin->w_cursor.col = 0;
  5740.  
  5741.         l = ml_get_curline();
  5742.  
  5743.         /*
  5744.          * If we're in a comment now, skip to the start of the comment.
  5745.          */                        /* XXX */
  5746.         if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
  5747.         {
  5748.             curwin->w_cursor.lnum = trypos->lnum + 1;
  5749.             continue;
  5750.         }
  5751.  
  5752.         /*
  5753.          * If the line looks like a function declaration, and we're
  5754.          * not in a comment, put it the left margin.
  5755.          */
  5756.         if (cin_isfuncdecl(theline))
  5757.             break;
  5758.  
  5759.         /*
  5760.          * Finding the closing '}' of a previous function.  Put
  5761.          * current line at the left margin.  For when 'cino' has "fs".
  5762.          */
  5763.         if (*skipwhite(l) == '}')
  5764.             break;
  5765.  
  5766.         /*
  5767.          * If the previous line ends on '};' (maybe followed by
  5768.          * comments) align at column 0.  For example:
  5769.          * char *string_array[] = { "foo",
  5770.          *     / * x * / "b};ar" }; / * foobar * /
  5771.          */
  5772.         if (cin_ends_in(l, (char_u *)"};"))
  5773.             break;
  5774.  
  5775.         /*
  5776.          * Skip preprocessor directives and blank lines.
  5777.          */
  5778.         if (cin_ispreproc(l))
  5779.             continue;
  5780.  
  5781.         if (cin_nocode(l))
  5782.             continue;
  5783.  
  5784.         /*
  5785.          * If the PREVIOUS line is a function declaration, the current
  5786.          * line (and the ones that follow) needs to be indented as
  5787.          * parameters.
  5788.          */
  5789.         if (cin_isfuncdecl(l))
  5790.         {
  5791.             amount = ind_param;
  5792.             break;
  5793.         }
  5794.  
  5795.         /*
  5796.          * If the previous line ends in ';' and the line before the
  5797.          * previous line ends in ',' or '\', ident to column zero:
  5798.          * int foo,
  5799.          *     bar;
  5800.          * indent_to_0 here;
  5801.          */
  5802.         if (cin_ends_in(l, (char_u*)";"))
  5803.         {
  5804.             l = ml_get(curwin->w_cursor.lnum - 1);
  5805.             if (cin_ends_in(l, (char_u *)",")
  5806.                 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
  5807.             break;
  5808.             l = ml_get_curline();
  5809.         }
  5810.  
  5811.         /*
  5812.          * If the previous line ends in ',', use one level of
  5813.          * indentation:
  5814.          * int foo,
  5815.          *     bar;
  5816.          */
  5817.         if (cin_ends_in(l, (char_u *)",")
  5818.             || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
  5819.         {
  5820.             amount = get_indent();
  5821.             if (amount == 0)
  5822.             amount = ind_param;
  5823.             break;
  5824.         }
  5825.  
  5826.         /*
  5827.          * Doesn't look like anything interesting -- so just
  5828.          * use the indent of this line.
  5829.          *
  5830.          * Position the cursor over the rightmost paren, so that
  5831.          * matching it will take us back to the start of the line.
  5832.          */
  5833.         find_last_paren(l);
  5834.  
  5835.         if ((trypos = find_match_paren(ind_maxparen,
  5836.                              ind_maxcomment)) != NULL)
  5837.             curwin->w_cursor.lnum = trypos->lnum;
  5838.         amount = get_indent();        /* XXX */
  5839.         break;
  5840.         }
  5841.     }
  5842.     }
  5843.  
  5844. theend:
  5845.     /* put the cursor back where it belongs */
  5846.     curwin->w_cursor = cur_curpos;
  5847.  
  5848.     vim_free(linecopy);
  5849.  
  5850.     if (amount < 0)
  5851.     return 0;
  5852.     return amount;
  5853. }
  5854.  
  5855.     static int
  5856. find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
  5857.     int        lookfor;
  5858.     linenr_T    ourscope;
  5859.     int        ind_maxparen;
  5860.     int        ind_maxcomment;
  5861. {
  5862.     char_u    *look;
  5863.     pos_T    *theirscope;
  5864.     char_u    *mightbeif;
  5865.     int        elselevel;
  5866.     int        whilelevel;
  5867.  
  5868.     if (lookfor == LOOKFOR_IF)
  5869.     {
  5870.     elselevel = 1;
  5871.     whilelevel = 0;
  5872.     }
  5873.     else
  5874.     {
  5875.     elselevel = 0;
  5876.     whilelevel = 1;
  5877.     }
  5878.  
  5879.     curwin->w_cursor.col = 0;
  5880.  
  5881.     while (curwin->w_cursor.lnum > ourscope + 1)
  5882.     {
  5883.     curwin->w_cursor.lnum--;
  5884.     curwin->w_cursor.col = 0;
  5885.  
  5886.     look = cin_skipcomment(ml_get_curline());
  5887.     if (cin_iselse(look)
  5888.         || cin_isif(look)
  5889.         || cin_isdo(look)                /* XXX */
  5890.         || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
  5891.     {
  5892.         /*
  5893.          * if we've gone outside the braces entirely,
  5894.          * we must be out of scope...
  5895.          */
  5896.         theirscope = find_start_brace(ind_maxcomment);  /* XXX */
  5897.         if (theirscope == NULL)
  5898.         break;
  5899.  
  5900.         /*
  5901.          * and if the brace enclosing this is further
  5902.          * back than the one enclosing the else, we're
  5903.          * out of luck too.
  5904.          */
  5905.         if (theirscope->lnum < ourscope)
  5906.         break;
  5907.  
  5908.         /*
  5909.          * and if they're enclosed in a *deeper* brace,
  5910.          * then we can ignore it because it's in a
  5911.          * different scope...
  5912.          */
  5913.         if (theirscope->lnum > ourscope)
  5914.         continue;
  5915.  
  5916.         /*
  5917.          * if it was an "else" (that's not an "else if")
  5918.          * then we need to go back to another if, so
  5919.          * increment elselevel
  5920.          */
  5921.         look = cin_skipcomment(ml_get_curline());
  5922.         if (cin_iselse(look))
  5923.         {
  5924.         mightbeif = cin_skipcomment(look + 4);
  5925.         if (!cin_isif(mightbeif))
  5926.             ++elselevel;
  5927.         continue;
  5928.         }
  5929.  
  5930.         /*
  5931.          * if it was a "while" then we need to go back to
  5932.          * another "do", so increment whilelevel.  XXX
  5933.          */
  5934.         if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
  5935.         {
  5936.         ++whilelevel;
  5937.         continue;
  5938.         }
  5939.  
  5940.         /* If it's an "if" decrement elselevel */
  5941.         look = cin_skipcomment(ml_get_curline());
  5942.         if (cin_isif(look))
  5943.         {
  5944.         elselevel--;
  5945.         /*
  5946.          * When looking for an "if" ignore "while"s that
  5947.          * get in the way.
  5948.          */
  5949.         if (elselevel == 0 && lookfor == LOOKFOR_IF)
  5950.             whilelevel = 0;
  5951.         }
  5952.  
  5953.         /* If it's a "do" decrement whilelevel */
  5954.         if (cin_isdo(look))
  5955.         whilelevel--;
  5956.  
  5957.         /*
  5958.          * if we've used up all the elses, then
  5959.          * this must be the if that we want!
  5960.          * match the indent level of that if.
  5961.          */
  5962.         if (elselevel <= 0 && whilelevel <= 0)
  5963.         {
  5964.         return OK;
  5965.         }
  5966.     }
  5967.     }
  5968.     return FAIL;
  5969. }
  5970.  
  5971. # if defined(FEAT_EVAL) || defined(PROTO)
  5972. /*
  5973.  * Get indent level from 'indentexpr'.
  5974.  */
  5975.     int
  5976. get_expr_indent()
  5977. {
  5978.     int        indent;
  5979.     pos_T    pos;
  5980.  
  5981.     pos = curwin->w_cursor;
  5982.     set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
  5983.     ++sandbox;
  5984.     indent = eval_to_number(curbuf->b_p_inde);
  5985.     --sandbox;
  5986.  
  5987.     /* restore the cursor position so that 'indentexpr' doesn't need to */
  5988.     curwin->w_cursor = pos;
  5989.     check_cursor();
  5990.  
  5991.     /* If there is an error, just keep the current indent. */
  5992.     if (indent < 0)
  5993.     indent = get_indent();
  5994.  
  5995.     return indent;
  5996. }
  5997. # endif
  5998.  
  5999. #endif /* FEAT_CINDENT */
  6000.  
  6001. #if defined(FEAT_LISP) || defined(PROTO)
  6002.  
  6003. static int lisp_match __ARGS((char_u *p));
  6004.  
  6005.     static int
  6006. lisp_match(p)
  6007.     char_u    *p;
  6008. {
  6009.     char_u    buf[LSIZE];
  6010.     int        len;
  6011.     char_u    *word = p_lispwords;
  6012.  
  6013.     while (*word != NUL)
  6014.     {
  6015.     (void)copy_option_part(&word, buf, LSIZE, ",");
  6016.     len = (int)STRLEN(buf);
  6017.     if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
  6018.         return TRUE;
  6019.     }
  6020.     return FALSE;
  6021. }
  6022.  
  6023. /*
  6024.  * When 'p' is present in 'cpoptions, a Vi compatible method is used.
  6025.  * The incompatible newer method is quite a bit better at indenting
  6026.  * code in lisp-like languages than the traditional one; it's still
  6027.  * mostly heuristics however -- Dirk van Deun, dirk@rave.org
  6028.  *
  6029.  * TODO:
  6030.  * Findmatch() should be adapted for lisp, also to make showmatch
  6031.  * work correctly: now (v5.3) it seems all C/C++ oriented:
  6032.  * - it does not recognize the #\( and #\) notations as character literals
  6033.  * - it doesn't know about comments starting with a semicolon
  6034.  * - it incorrectly interprets '(' as a character literal
  6035.  * All this messes up get_lisp_indent in some rare cases.
  6036.  */
  6037.     int
  6038. get_lisp_indent()
  6039. {
  6040.     pos_T    *pos, realpos;
  6041.     int        amount;
  6042.     char_u    *that;
  6043.     colnr_T    col;
  6044.     colnr_T    firsttry;
  6045.     int        parencount, quotecount;
  6046.     int        vi_lisp;
  6047.  
  6048.     /* Set vi_lisp to use the vi-compatible method */
  6049.     vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
  6050.  
  6051.     realpos = curwin->w_cursor;
  6052.     curwin->w_cursor.col = 0;
  6053.  
  6054.     if ((pos = findmatch(NULL, '(')) != NULL)
  6055.     {
  6056.     /* Extra trick: Take the indent of the first previous non-white
  6057.      * line that is at the same () level. */
  6058.     amount = -1;
  6059.     parencount = 0;
  6060.  
  6061.     while (--curwin->w_cursor.lnum >= pos->lnum)
  6062.     {
  6063.         if (linewhite(curwin->w_cursor.lnum))
  6064.         continue;
  6065.         for (that = ml_get_curline(); *that != NUL; ++that)
  6066.         {
  6067.         if (*that == ';')
  6068.         {
  6069.             while (*(that + 1) != NUL)
  6070.             ++that;
  6071.             continue;
  6072.         }
  6073.         if (*that == '\\')
  6074.         {
  6075.             if (*(that + 1) != NUL)
  6076.             ++that;
  6077.             continue;
  6078.         }
  6079.         if (*that == '"' && *(that + 1) != NUL)
  6080.         {
  6081.             that++;
  6082.             while (*that && (*that != '"' || *(that - 1) == '\\'))
  6083.             ++that;
  6084.         }
  6085.         if (*that == '(')
  6086.             ++parencount;
  6087.         else if (*that == ')')
  6088.             --parencount;
  6089.         }
  6090.         if (parencount == 0)
  6091.         {
  6092.         amount = get_indent();
  6093.         break;
  6094.         }
  6095.     }
  6096.  
  6097.     if (amount == -1)
  6098.     {
  6099.         curwin->w_cursor.lnum = pos->lnum;
  6100.         curwin->w_cursor.col = pos->col;
  6101.         col = pos->col;
  6102.  
  6103.         that = ml_get_curline();
  6104.  
  6105.         if (vi_lisp && get_indent() == 0)
  6106.         amount = 2;
  6107.         else
  6108.         {
  6109.         amount = 0;
  6110.         while (*that && col)
  6111.         {
  6112.             amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
  6113.             col--;
  6114.         }
  6115.  
  6116.         /*
  6117.          * Some keywords require "body" indenting rules (the
  6118.          * non-standard-lisp ones are Scheme special forms):
  6119.          *
  6120.          * (let ((a 1))    instead    (let ((a 1))
  6121.          *   (...))          of       (...))
  6122.          */
  6123.  
  6124.         if (!vi_lisp && *that == '(' && lisp_match(that + 1))
  6125.             amount += 2;
  6126.         else
  6127.         {
  6128.             that++;
  6129.             amount++;
  6130.             firsttry = amount;
  6131.  
  6132.             while (vim_iswhite(*that))
  6133.             {
  6134.             amount += lbr_chartabsize(that, (colnr_T)amount);
  6135.             ++that;
  6136.             }
  6137.  
  6138.             if (*that && *that != ';') /* not a comment line */
  6139.             {
  6140.             /* test *that != '(' to accomodate first let/do
  6141.              * argument if it is more than one line */
  6142.             if (!vi_lisp && *that != '(')
  6143.                 firsttry++;
  6144.  
  6145.             parencount = 0;
  6146.             quotecount = 0;
  6147.  
  6148.             if (vi_lisp
  6149.                 || (*that != '"'
  6150.                     && *that != '\''
  6151.                     && *that != '#'
  6152.                     && (*that < '0' || *that > '9')))
  6153.             {
  6154.                 while (*that
  6155.                     && (!vim_iswhite(*that)
  6156.                     || quotecount
  6157.                     || parencount)
  6158.                     && (!(*that == '('
  6159.                         && !quotecount
  6160.                         && !parencount
  6161.                         && vi_lisp)))
  6162.                 {
  6163.                 if (*that == '"')
  6164.                     quotecount = !quotecount;
  6165.                 if (*that == '(' && !quotecount)
  6166.                     ++parencount;
  6167.                 if (*that == ')' && !quotecount)
  6168.                     --parencount;
  6169.                 if (*that == '\\' && *(that+1) != NUL)
  6170.                     amount += lbr_chartabsize_adv(&that,
  6171.                                  (colnr_T)amount);
  6172.                 amount += lbr_chartabsize_adv(&that,
  6173.                                  (colnr_T)amount);
  6174.                 }
  6175.             }
  6176.             while (vim_iswhite(*that))
  6177.             {
  6178.                 amount += lbr_chartabsize(that, (colnr_T)amount);
  6179.                 that++;
  6180.             }
  6181.             if (!*that || *that == ';')
  6182.                 amount = firsttry;
  6183.             }
  6184.         }
  6185.         }
  6186.     }
  6187.     }
  6188.     else
  6189.     amount = 0;    /* no matching '(' found, use zero indent */
  6190.  
  6191.     curwin->w_cursor = realpos;
  6192.  
  6193.     return amount;
  6194. }
  6195. #endif /* FEAT_LISP */
  6196.  
  6197.     void
  6198. prepare_to_exit()
  6199. {
  6200. #ifdef FEAT_GUI
  6201.     if (gui.in_use)
  6202.     {
  6203.     gui.dying = TRUE;
  6204.     out_trash();    /* trash any pending output */
  6205.     }
  6206.     else
  6207. #endif
  6208.     {
  6209.     windgoto((int)Rows - 1, 0);
  6210.  
  6211.     /*
  6212.      * Switch terminal mode back now, so messages end up on the "normal"
  6213.      * screen (if there are two screens).
  6214.      */
  6215.     settmode(TMODE_COOK);
  6216. #ifdef WIN3264
  6217.     if (can_end_termcap_mode(FALSE) == TRUE)
  6218. #endif
  6219.         stoptermcap();
  6220.     out_flush();
  6221.     }
  6222. }
  6223.  
  6224. /*
  6225.  * Preserve files and exit.
  6226.  * When called IObuff must contain a message.
  6227.  */
  6228.     void
  6229. preserve_exit()
  6230. {
  6231.     buf_T    *buf;
  6232.  
  6233.     prepare_to_exit();
  6234.  
  6235.     out_str(IObuff);
  6236.     screen_start();            /* don't know where cursor is now */
  6237.     out_flush();
  6238.  
  6239.     ml_close_notmod();            /* close all not-modified buffers */
  6240.  
  6241.     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
  6242.     {
  6243.     if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
  6244.     {
  6245.         OUT_STR(_("Vim: preserving files...\n"));
  6246.         screen_start();        /* don't know where cursor is now */
  6247.         out_flush();
  6248.         ml_sync_all(FALSE, FALSE);    /* preserve all swap files */
  6249.         break;
  6250.     }
  6251.     }
  6252.  
  6253.     ml_close_all(FALSE);        /* close all memfiles, without deleting */
  6254.  
  6255.     OUT_STR(_("Vim: Finished.\n"));
  6256.  
  6257.     getout(1);
  6258. }
  6259.  
  6260. /*
  6261.  * return TRUE if "fname" exists.
  6262.  */
  6263.     int
  6264. vim_fexists(fname)
  6265.     char_u  *fname;
  6266. {
  6267.     struct stat st;
  6268.  
  6269.     if (mch_stat((char *)fname, &st))
  6270.     return FALSE;
  6271.     return TRUE;
  6272. }
  6273.  
  6274. /*
  6275.  * Check for CTRL-C pressed, but only once in a while.
  6276.  * Should be used instead of ui_breakcheck() for functions that check for
  6277.  * each line in the file.  Calling ui_breakcheck() each time takes too much
  6278.  * time, because it can be a system call.
  6279.  */
  6280.  
  6281. #ifndef BREAKCHECK_SKIP
  6282. # ifdef FEAT_GUI            /* assume the GUI only runs on fast computers */
  6283. #  define BREAKCHECK_SKIP 200
  6284. # else
  6285. #  define BREAKCHECK_SKIP 32
  6286. # endif
  6287. #endif
  6288.  
  6289. static int    breakcheck_count = 0;
  6290.  
  6291.     void
  6292. line_breakcheck()
  6293. {
  6294.     if (++breakcheck_count >= BREAKCHECK_SKIP)
  6295.     {
  6296.     breakcheck_count = 0;
  6297.     ui_breakcheck();
  6298.     }
  6299. }
  6300.  
  6301. /*
  6302.  * Like line_breakcheck() but check 10 times less often.
  6303.  */
  6304.     void
  6305. fast_breakcheck()
  6306. {
  6307.     if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
  6308.     {
  6309.     breakcheck_count = 0;
  6310.     ui_breakcheck();
  6311.     }
  6312. }
  6313.  
  6314. /*
  6315.  * Expand wildcards.  Calls gen_expand_wildcards() and removes files matching
  6316.  * 'wildignore'.
  6317.  */
  6318.     int
  6319. expand_wildcards(num_pat, pat, num_file, file, flags)
  6320.     int           num_pat;    /* number of input patterns */
  6321.     char_u     **pat;        /* array of input patterns */
  6322.     int          *num_file;    /* resulting number of files */
  6323.     char_u    ***file;    /* array of resulting files */
  6324.     int           flags;    /* EW_DIR, etc. */
  6325. {
  6326.     int        retval;
  6327.     int        i, j;
  6328.     char_u    *p;
  6329.     int        non_suf_match;    /* number without matching suffix */
  6330.  
  6331.     retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
  6332.  
  6333.     /* When keeping all matches, return here */
  6334.     if (flags & EW_KEEPALL)
  6335.     return retval;
  6336.  
  6337. #ifdef FEAT_WILDIGN
  6338.     /*
  6339.      * Remove names that match 'wildignore'.
  6340.      */
  6341.     if (*p_wig)
  6342.     {
  6343.     char_u    *ffname;
  6344.  
  6345.     /* check all files in (*file)[] */
  6346.     for (i = 0; i < *num_file; ++i)
  6347.     {
  6348.         ffname = FullName_save((*file)[i], FALSE);
  6349.         if (ffname == NULL)        /* out of memory */
  6350.         break;
  6351. #ifdef VMS
  6352.         vms_remove_version(ffname);
  6353. #endif
  6354.         if (match_file_list(p_wig, (*file)[i], ffname))
  6355.         {
  6356.         /* remove this matching file from the list */
  6357.         vim_free((*file)[i]);
  6358.         for (j = i; j + 1 < *num_file; ++j)
  6359.             (*file)[j] = (*file)[j + 1];
  6360.         --*num_file;
  6361.         --i;
  6362.         }
  6363.         vim_free(ffname);
  6364.     }
  6365.     }
  6366. #endif
  6367.  
  6368.     /*
  6369.      * Move the names where 'suffixes' match to the end.
  6370.      */
  6371.     if (*num_file > 1)
  6372.     {
  6373.     non_suf_match = 0;
  6374.     for (i = 0; i < *num_file; ++i)
  6375.     {
  6376.         if (!match_suffix((*file)[i]))
  6377.         {
  6378.         /*
  6379.          * Move the name without matching suffix to the front
  6380.          * of the list.
  6381.          */
  6382.         p = (*file)[i];
  6383.         for (j = i; j > non_suf_match; --j)
  6384.             (*file)[j] = (*file)[j - 1];
  6385.         (*file)[non_suf_match++] = p;
  6386.         }
  6387.     }
  6388.     }
  6389.  
  6390.     return retval;
  6391. }
  6392.  
  6393. /*
  6394.  * Return TRUE if "fname" matches with an entry in 'suffixes'.
  6395.  */
  6396.     int
  6397. match_suffix(fname)
  6398.     char_u    *fname;
  6399. {
  6400.     int        fnamelen, setsuflen;
  6401.     char_u    *setsuf;
  6402. #define MAXSUFLEN 30        /* maximum length of a file suffix */
  6403.     char_u    suf_buf[MAXSUFLEN];
  6404.  
  6405.     fnamelen = (int)STRLEN(fname);
  6406.     setsuflen = 0;
  6407.     for (setsuf = p_su; *setsuf; )
  6408.     {
  6409.     setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
  6410.     if (fnamelen >= setsuflen
  6411.         && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
  6412.                           (size_t)setsuflen) == 0)
  6413.         break;
  6414.     setsuflen = 0;
  6415.     }
  6416.     return (setsuflen != 0);
  6417. }
  6418.  
  6419. #if !defined(NO_EXPANDPATH) || defined(PROTO)
  6420.  
  6421. # ifdef VIM_BACKTICK
  6422. static int vim_backtick __ARGS((char_u *p));
  6423. static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
  6424. # endif
  6425.  
  6426. # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
  6427. /*
  6428.  * File name expansion code for MS-DOS, Win16 and Win32.  It's here because
  6429.  * it's shared between these systems.
  6430.  */
  6431. # if defined(DJGPP) || defined(PROTO)
  6432. #  define _cdecl        /* DJGPP doesn't have this */
  6433. # else
  6434. #  ifdef __BORLANDC__
  6435. #   define _cdecl _RTLENTRYF
  6436. #  endif
  6437. # endif
  6438.  
  6439. /*
  6440.  * comparison function for qsort in dos_expandpath()
  6441.  */
  6442.     static int _cdecl
  6443. pstrcmp(const void *a, const void *b)
  6444. {
  6445.     return (pathcmp(*(char **)a, *(char **)b));
  6446. }
  6447.  
  6448. # ifndef WIN3264
  6449.     static void
  6450. namelowcpy(
  6451.     char_u *d,
  6452.     char_u *s)
  6453. {
  6454. #  ifdef DJGPP
  6455.     if (USE_LONG_FNAME)        /* don't lower case on Windows 95/NT systems */
  6456.     while (*s)
  6457.         *d++ = *s++;
  6458.     else
  6459. #  endif
  6460.     while (*s)
  6461.         *d++ = TO_LOWER(*s++);
  6462.     *d = NUL;
  6463. }
  6464. # endif
  6465.  
  6466. /*
  6467.  * Recursively build up a list of files in "gap" matching the first wildcard
  6468.  * in `path'.  Called by expand_wildcards().
  6469.  * Return the number of matches found.
  6470.  * "path" has backslashes before chars that are not to be expanded, starting
  6471.  * at "wildc".
  6472.  */
  6473.     static int
  6474. dos_expandpath(
  6475.     garray_T    *gap,
  6476.     char_u    *path,
  6477.     char_u    *wildc,
  6478.     int        flags)        /* EW_* flags */
  6479. {
  6480.     char_u        *buf;
  6481.     char_u        *p, *s, *e;
  6482.     int            start_len = gap->ga_len;
  6483.     int            ok;
  6484. #ifdef WIN3264
  6485.     WIN32_FIND_DATA    fb;
  6486.     HANDLE        hFind;
  6487. #else
  6488.     struct ffblk    fb;
  6489. #endif
  6490.     int            matches;
  6491.     int            starts_with_dot;
  6492.     int            len;
  6493.     char_u        *pat;
  6494.     regmatch_T        regmatch;
  6495.     char_u        *matchname;
  6496.  
  6497.     /* make room for file name */
  6498.     buf = alloc((unsigned int)STRLEN(path) + BASENAMELEN + 5);
  6499.     if (buf == NULL)
  6500.     return 0;
  6501.  
  6502.     /*
  6503.      * Find the first part in the path name that contains a wildcard or a ~1.
  6504.      * Copy it into buf, including the preceding characters.
  6505.      */
  6506.     p = buf;
  6507.     s = buf;
  6508.     e = NULL;
  6509.     while (*path != NUL)
  6510.     {
  6511.     if (path >= wildc && rem_backslash(path))    /* remove a backslash */
  6512.         ++path;
  6513.     else if (*path == '\\' || *path == ':' || *path == '/')
  6514.     {
  6515.         if (e != NULL)
  6516.         break;
  6517.         else
  6518.         s = p + 1;
  6519.     }
  6520.     else if (path >= wildc && (*path == '*' || *path == '?'
  6521.                          || *path == '[' || *path == '~'))
  6522.         e = p;
  6523. #ifdef FEAT_MBYTE
  6524.     if (has_mbyte)
  6525.     {
  6526.         len = (*mb_ptr2len_check)(path);
  6527.         STRNCPY(p, path, len);
  6528.         p += len;
  6529.         path += len;
  6530.     }
  6531.     else
  6532. #endif
  6533.         *p++ = *path++;
  6534.     }
  6535.     e = p;
  6536.     *e = NUL;
  6537.     /* now we have one wildcard component between s and e */
  6538.  
  6539.     starts_with_dot = (*s == '.');
  6540.     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
  6541.     if (pat == NULL)
  6542.     {
  6543.     vim_free(buf);
  6544.     return 0;
  6545.     }
  6546.  
  6547.     /* compile the regexp into a program */
  6548.     regmatch.rm_ic = TRUE;        /* Always ignore case */
  6549.     regmatch.regprog = vim_regcomp(pat, TRUE);
  6550.     vim_free(pat);
  6551.  
  6552.     if (regmatch.regprog == NULL)
  6553.     {
  6554.     vim_free(buf);
  6555.     return 0;
  6556.     }
  6557.  
  6558.     /* remember the pattern or file name being looked for */
  6559.     matchname = vim_strsave(s);
  6560.  
  6561.     /* Scan all files in the directory with "dir/ *.*" */
  6562.     STRCPY(s, "*.*");
  6563. #ifdef WIN3264
  6564.     hFind = FindFirstFile(buf, &fb);
  6565.     ok = (hFind != INVALID_HANDLE_VALUE);
  6566. #else
  6567.     /* If we are expanding wildcards we try both files and directories */
  6568.     ok = (findfirst((char *)buf, &fb,
  6569.                 (*path || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
  6570. #endif
  6571.  
  6572.     while (ok)
  6573.     {
  6574. #ifdef WIN3264
  6575.     p = (char_u *)fb.cFileName;
  6576. #else
  6577.     p = (char_u *)fb.ff_name;
  6578. #endif
  6579.     /* Ignore entries starting with a dot, unless when asked for.  Accept
  6580.      * all entries found with "matchname". */
  6581.     if ((p[0] != '.' || starts_with_dot)
  6582.         && (matchname == NULL
  6583.             || vim_regexec(®match, p, (colnr_T)0)))
  6584.     {
  6585. #ifdef WIN3264
  6586.         STRCPY(s, p);
  6587. #else
  6588.         namelowcpy(s, p);
  6589. #endif
  6590.         len = (int)STRLEN(buf);
  6591.         STRCPY(buf + len, path);
  6592.         if (mch_has_exp_wildcard(path))
  6593.         {
  6594.         /* need to expand another component of the path */
  6595.         /* remove backslashes for the remaining components only */
  6596.         (void)dos_expandpath(gap, buf, buf + len + 1, flags);
  6597.         }
  6598.         else
  6599.         {
  6600.         /* no more wildcards, check if there is a match */
  6601.         /* remove backslashes for the remaining components only */
  6602.         if (*path)
  6603.             backslash_halve(buf + len + 1);
  6604.         if (mch_getperm(buf) >= 0)    /* add existing file */
  6605.             addfile(gap, buf, flags);
  6606.         }
  6607.     }
  6608. #ifdef WIN3264
  6609.     ok = FindNextFile(hFind, &fb);
  6610. #else
  6611.     ok = (findnext(&fb) == 0);
  6612. #endif
  6613.  
  6614.     /* If no more matches and no match was used, try expanding the name
  6615.      * itself.  Finds the long name of a short filename. */
  6616.     if (!ok && matchname != NULL && gap->ga_len == start_len)
  6617.     {
  6618.         STRCPY(s, matchname);
  6619. #ifdef WIN3264
  6620.         FindClose(hFind);
  6621.         hFind = FindFirstFile(buf, &fb);
  6622.         ok = (hFind != INVALID_HANDLE_VALUE);
  6623. #else
  6624.         ok = (findfirst((char *)buf, &fb,
  6625.                 (*path || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
  6626. #endif
  6627.         vim_free(matchname);
  6628.         matchname = NULL;
  6629.     }
  6630.     }
  6631.  
  6632. #ifdef WIN3264
  6633.     FindClose(hFind);
  6634. #endif
  6635.     vim_free(buf);
  6636.     vim_free(regmatch.regprog);
  6637.     vim_free(matchname);
  6638.  
  6639.     matches = gap->ga_len - start_len;
  6640.     if (matches)
  6641.     qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
  6642.                            sizeof(char_u *), pstrcmp);
  6643.     return matches;
  6644. }
  6645.  
  6646.     int
  6647. mch_expandpath(
  6648.     garray_T    *gap,
  6649.     char_u    *path,
  6650.     int        flags)        /* EW_* flags */
  6651. {
  6652.     return dos_expandpath(gap, path, path, flags);
  6653. }
  6654. # endif /* MSDOS || FEAT_GUI_W16 */
  6655.  
  6656. /*
  6657.  * Generic wildcard expansion code.
  6658.  *
  6659.  * Characters in "pat" that should not be expanded must be preceded with a
  6660.  * backslash. E.g., "/path\ with\ spaces/my\*star*"
  6661.  *
  6662.  * Return FAIL when no single file was found.  In this case "num_file" is not
  6663.  * set, and "file" may contain an error message.
  6664.  * Return OK when some files found.  "num_file" is set to the number of
  6665.  * matches, "file" to the array of matches.  Call FreeWild() later.
  6666.  */
  6667.     int
  6668. gen_expand_wildcards(num_pat, pat, num_file, file, flags)
  6669.     int        num_pat;    /* number of input patterns */
  6670.     char_u    **pat;        /* array of input patterns */
  6671.     int        *num_file;    /* resulting number of files */
  6672.     char_u    ***file;    /* array of resulting files */
  6673.     int        flags;        /* EW_* flags */
  6674. {
  6675.     int            i;
  6676.     garray_T        ga;
  6677.     char_u        *p;
  6678.     static int        recursive = FALSE;
  6679.     int            add_pat;
  6680.  
  6681.     /*
  6682.      * expand_env() is called to expand things like "~user".  If this fails,
  6683.      * it calls ExpandOne(), which brings us back here.  In this case, always
  6684.      * call the machine specific expansion function, if possible.  Otherwise,
  6685.      * return FAIL.
  6686.      */
  6687.     if (recursive)
  6688. #ifdef SPECIAL_WILDCHAR
  6689.     return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
  6690. #else
  6691.     return FAIL;
  6692. #endif
  6693.  
  6694. #ifdef SPECIAL_WILDCHAR
  6695.     /*
  6696.      * If there are any special wildcard characters which we cannot handle
  6697.      * here, call machine specific function for all the expansion.  This
  6698.      * avoids starting the shell for each argument separately.
  6699.      * For `=expr` do use the internal function.
  6700.      */
  6701.     for (i = 0; i < num_pat; i++)
  6702.     {
  6703.     if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
  6704. # ifdef VIM_BACKTICK
  6705.         && !(vim_backtick(pat[i]) && pat[i][1] == '=')
  6706. # endif
  6707.        )
  6708.         return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
  6709.     }
  6710. #endif
  6711.  
  6712.     recursive = TRUE;
  6713.  
  6714.     /*
  6715.      * The matching file names are stored in a growarray.  Init it empty.
  6716.      */
  6717.     ga_init2(&ga, (int)sizeof(char_u *), 30);
  6718.  
  6719.     for (i = 0; i < num_pat; ++i)
  6720.     {
  6721.     add_pat = -1;
  6722.     p = pat[i];
  6723.  
  6724. #ifdef VIM_BACKTICK
  6725.     if (vim_backtick(p))
  6726.         add_pat = expand_backtick(&ga, p, flags);
  6727.     else
  6728. #endif
  6729.     {
  6730.         /*
  6731.          * First expand environment variables, "~/" and "~user/".
  6732.          */
  6733.         if (vim_strpbrk(p, (char_u *)"$~") != NULL)
  6734.         {
  6735.         p = expand_env_save(p);
  6736.         if (p == NULL)
  6737.             p = pat[i];
  6738. #ifdef UNIX
  6739.         /*
  6740.          * On Unix, if expand_env() can't expand an environment
  6741.          * variable, use the shell to do that.  Discard previously
  6742.          * found file names and start all over again.
  6743.          */
  6744.         else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
  6745.         {
  6746.             vim_free(p);
  6747.             ga_clear(&ga);
  6748.             i = mch_expand_wildcards(num_pat, pat, num_file, file,
  6749.                                        flags);
  6750.             recursive = FALSE;
  6751.             return i;
  6752.         }
  6753. #endif
  6754.         }
  6755.  
  6756.         /*
  6757.          * If there are wildcards: Expand file names and add each match to
  6758.          * the list.  If there is no match, and EW_NOTFOUND is given, add
  6759.          * the pattern.
  6760.          * If there are no wildcards: Add the file name if it exists or
  6761.          * when EW_NOTFOUND is given.
  6762.          */
  6763.         if (mch_has_exp_wildcard(p))
  6764.         add_pat = mch_expandpath(&ga, p, flags);
  6765.     }
  6766.  
  6767.     if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
  6768.     {
  6769.         char_u    *t = backslash_halve_save(p);
  6770.  
  6771. #if defined(MACOS_CLASSIC)
  6772.         slash_to_colon(t);
  6773. #endif
  6774.         /* When EW_NOTFOUND is used, always add files and dirs.  Makes
  6775.          * "vim c:/" work. */
  6776.         if (flags & EW_NOTFOUND)
  6777.         addfile(&ga, t, flags | EW_DIR | EW_FILE);
  6778.         else if (mch_getperm(t) >= 0)
  6779.         addfile(&ga, t, flags);
  6780.         vim_free(t);
  6781.     }
  6782.  
  6783.     if (p != pat[i])
  6784.         vim_free(p);
  6785.     }
  6786.  
  6787.     *num_file = ga.ga_len;
  6788.     *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
  6789.  
  6790.     recursive = FALSE;
  6791.  
  6792.     return (ga.ga_data != NULL) ? OK : FAIL;
  6793. }
  6794.  
  6795. # ifdef VIM_BACKTICK
  6796.  
  6797. /*
  6798.  * Return TRUE if we can expand this backtick thing here.
  6799.  */
  6800.     static int
  6801. vim_backtick(p)
  6802.     char_u    *p;
  6803. {
  6804.     return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
  6805. }
  6806.  
  6807. /*
  6808.  * Expand an item in `backticks` by executing it as a command.
  6809.  * Currently only works when pat[] starts and ends with a `.
  6810.  * Returns number of file names found.
  6811.  */
  6812.     static int
  6813. expand_backtick(gap, pat, flags)
  6814.     garray_T    *gap;
  6815.     char_u    *pat;
  6816.     int        flags;    /* EW_* flags */
  6817. {
  6818.     char_u    *p;
  6819.     char_u    *cmd;
  6820.     char_u    *buffer;
  6821.     int        cnt = 0;
  6822.     int        i;
  6823.  
  6824.     /* Create the command: lop off the backticks. */
  6825.     cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
  6826.     if (cmd == NULL)
  6827.     return 0;
  6828.  
  6829. #ifdef FEAT_EVAL
  6830.     if (*cmd == '=')        /* `={expr}`: Expand expression */
  6831.     buffer = eval_to_string(cmd + 1, &p);
  6832.     else
  6833. #endif
  6834.     buffer = get_cmd_output(cmd, (flags & EW_SILENT) ? SHELL_SILENT : 0);
  6835.     vim_free(cmd);
  6836.     if (buffer == NULL)
  6837.     return 0;
  6838.  
  6839.     cmd = buffer;
  6840.     while (*cmd != NUL)
  6841.     {
  6842.     cmd = skipwhite(cmd);        /* skip over white space */
  6843.     p = cmd;
  6844.     while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
  6845.         ++p;
  6846.     /* add an entry if it is not empty */
  6847.     if (p > cmd)
  6848.     {
  6849.         i = *p;
  6850.         *p = NUL;
  6851.         addfile(gap, cmd, flags);
  6852.         *p = i;
  6853.         ++cnt;
  6854.     }
  6855.     cmd = p;
  6856.     while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
  6857.         ++cmd;
  6858.     }
  6859.  
  6860.     vim_free(buffer);
  6861.     return cnt;
  6862. }
  6863. # endif /* VIM_BACKTICK */
  6864.  
  6865. /*
  6866.  * Add a file to a file list.  Accepted flags:
  6867.  * EW_DIR    add directories
  6868.  * EW_FILE    add files
  6869.  * EW_NOTFOUND    add even when it doesn't exist
  6870.  * EW_ADDSLASH    add slash after directory name
  6871.  */
  6872.     void
  6873. addfile(gap, f, flags)
  6874.     garray_T    *gap;
  6875.     char_u    *f;    /* filename */
  6876.     int        flags;
  6877. {
  6878.     char_u    *p;
  6879.     int        isdir;
  6880.  
  6881.     /* if the file/dir doesn't exist, may not add it */
  6882.     if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
  6883.     return;
  6884.  
  6885. #ifdef FNAME_ILLEGAL
  6886.     /* if the file/dir contains illegal characters, don't add it */
  6887.     if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
  6888.     return;
  6889. #endif
  6890.  
  6891.     isdir = mch_isdir(f);
  6892.     if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
  6893.     return;
  6894.  
  6895.     /* Make room for another item in the file list. */
  6896.     if (ga_grow(gap, 1) == FAIL)
  6897.     return;
  6898.  
  6899.     p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
  6900.     if (p == NULL)
  6901.     return;
  6902.  
  6903.     STRCPY(p, f);
  6904. #ifdef BACKSLASH_IN_FILENAME
  6905.     slash_adjust(p);
  6906. #endif
  6907.     /*
  6908.      * Append a slash or backslash after directory names if none is present.
  6909.      */
  6910. #ifndef DONT_ADD_PATHSEP_TO_DIR
  6911.     if (isdir && (flags & EW_ADDSLASH))
  6912.     add_pathsep(p);
  6913. #endif
  6914.     ((char_u **)gap->ga_data)[gap->ga_len++] = p;
  6915.     --gap->ga_room;
  6916. }
  6917. #endif /* !NO_EXPANDPATH */
  6918.  
  6919. #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
  6920.  
  6921. #ifndef SEEK_SET
  6922. # define SEEK_SET 0
  6923. #endif
  6924. #ifndef SEEK_END
  6925. # define SEEK_END 2
  6926. #endif
  6927.  
  6928. /*
  6929.  * Get the stdout of an external command.
  6930.  * Returns an allocated string, or NULL for error.
  6931.  */
  6932.     char_u *
  6933. get_cmd_output(cmd, flags)
  6934.     char_u    *cmd;
  6935.     int        flags;        /* can be SHELL_SILENT */
  6936. {
  6937.     char_u    *tempname;
  6938.     char_u    *command;
  6939.     char_u    *buffer = NULL;
  6940.     int        len;
  6941.     int        i = 0;
  6942.     FILE    *fd;
  6943.  
  6944.     if (check_restricted() || check_secure())
  6945.     return NULL;
  6946.  
  6947.     /* get a name for the temp file */
  6948.     if ((tempname = vim_tempname('o')) == NULL)
  6949.     {
  6950.     EMSG(_(e_notmp));
  6951.     return NULL;
  6952.     }
  6953.  
  6954.     /* Add the redirection stuff */
  6955.     command = make_filter_cmd(cmd, NULL, tempname);
  6956.     if (command == NULL)
  6957.     goto done;
  6958.  
  6959.     /*
  6960.      * Call the shell to execute the command (errors are ignored).
  6961.      */
  6962.     call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
  6963.     vim_free(command);
  6964.  
  6965.     /*
  6966.      * read the names from the file into memory
  6967.      */
  6968.     fd = mch_fopen((char *)tempname, "r");
  6969.     if (fd == NULL)
  6970.     {
  6971.     EMSG2(_(e_notopen), tempname);
  6972.     goto done;
  6973.     }
  6974.  
  6975.     fseek(fd, 0L, SEEK_END);
  6976.     len = ftell(fd);            /* get size of temp file */
  6977.     fseek(fd, 0L, SEEK_SET);
  6978.  
  6979.     buffer = alloc(len + 1);
  6980.     if (buffer != NULL)
  6981.     i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
  6982.     fclose(fd);
  6983.     mch_remove(tempname);
  6984.     if (buffer == NULL)
  6985.     goto done;
  6986.     if (i != len)
  6987.     {
  6988.     EMSG2(_(e_notread), tempname);
  6989.     vim_free(buffer);
  6990.     buffer = NULL;
  6991.     }
  6992.     else
  6993.     buffer[len] = '\0';    /* make sure the buffer is terminated */
  6994.  
  6995. done:
  6996.     vim_free(tempname);
  6997.     return buffer;
  6998. }
  6999. #endif
  7000.  
  7001. /*
  7002.  * Free the list of files returned by expand_wildcards() or other expansion
  7003.  * functions.
  7004.  */
  7005.     void
  7006. FreeWild(count, files)
  7007.     int        count;
  7008.     char_u  **files;
  7009. {
  7010.     if (files == NULL || count <= 0)
  7011.     return;
  7012. #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
  7013.     /*
  7014.      * Is this still OK for when other functions than expand_wildcards() have
  7015.      * been used???
  7016.      */
  7017.     _fnexplodefree((char **)files);
  7018. #else
  7019.     while (count--)
  7020.     vim_free(files[count]);
  7021.     vim_free(files);
  7022. #endif
  7023. }
  7024.  
  7025. /*
  7026.  * return TRUE when need to go to Insert mode because of 'insertmode'.
  7027.  * Don't do this when still processing a command or a mapping.
  7028.  * Don't do this when inside a ":normal" command.
  7029.  */
  7030.     int
  7031. goto_im()
  7032. {
  7033.     return (p_im && stuff_empty() && typebuf_typed());
  7034. }
  7035.